Click here to Skip to main content
15,881,204 members
Articles / .NET
Alternative
Tip/Trick

Premature .NET garbage collection, or "Dude, where's my FooBar?"

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
29 Aug 2011CPOL1 min read 8.3K   2
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...

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 Disposes it, since the compiler will have to keep the object around at least until the Dispose call.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Unknown
Embedded systems programmer since 1994.

Comments and Discussions

 
GeneralI agree that it is curious that the KeepAlive call is necess... Pin
Phil Atkin29-Aug-11 0:25
Phil Atkin29-Aug-11 0:25 
GeneralRe: KeepAlive can be required even in 100% managed code, if a co... Pin
supercat929-Aug-11 11:51
supercat929-Aug-11 11:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.