It would be very nice if one could ask the .NET compilers to automatically add GC.KeepAlive(this)
to the end of a class' methods; IMHO, that should have been a default behavior for classes that override Finalize
. Unfortunately, since that isn't possible, one should probably, as a matter of course, include GC.KeepAlive(this)
to the end of any class method which overrides Finalize
.
I find it in a way curious that the creators of .NET seemed to expect Finalize
to be the primary means of cleaning up after objects are no longer needed, while Dispose
was something of an afterthought. While there are some scenarios where proper use of Dispose
would be difficult or impractical, there are so many cases where Finalize
really isn't sufficient, and so many more cases where it can lead to hard-to-track bugs, that I would in many cases think it better for a class to require the use of Dispose
for correct operation, than for it to attempt cleanup using Finalize
(using Finalize
to sound an alarm if a class isn't disposed may be a good idea, though). Among other things, if a class never attempts cleanup via Finalize
, failure to Dispose
will often yield consequences which are highly visible, and thus are likely to be diagnosed and fixed. By contrast, if a class overrides Finalize
to perform silent cleanup in case of a missing Dispose
, it's more likely that a missing Dispose
will go unnoticed, and there's a significant chance that a missing KeepAlive
will cause random failures. Note that a missing KeepAlive
will generally not cause trouble if the user of a class properly Dispose
s it, since the compiler will have to keep the object around at least until the Dispose
call.