Next generation's garbage RSS 2.0
# Monday, October 19, 2009
I'm actually going to encourage you to consider using GC methods. Well, now hang on cowboys... this is for pretty limited circumstances.

You see, the GC class can do more than compact memory. It can also run finalizers on unreferenced objects. If you are writing a class that included a finalizer (which you would only need if your class is the lowest-level class to deal with an unmanaged resource or are managing a pool of scarce resources) then you might consider using GC. Even though you might (read should) implement IDisposable, if a user of your library fails to Dispose your object, that unmanaged resource will leak until, at some non-deterministic (read random) point, the garbage collector runs and that object's finalizer might (read random) be queued and run. If this happens often enough, your attempt to create additional objects with the unmanaged resource could fail because you have exhausted the available supply.

Rather than fail, you could attempt:

 GC.Collect(0);
 GC.WaitForPendingFinalizers();

and try again. If it works on the retry, you might want to log that for the developer's information. One might argue that this is just encouraging and forgiving sloppiness, but I look at it as a step towards robustness and can actually help the developer diagnose a real problem whereas not doing this would just lead to more random run-time only-on-heavy-load failures.

If you wanted to be really awesome, once you detect that you could recover, flip a bit on to start recording a stacktrace on each create, then in your finalizer, put that stacktrace in a application-wide queue that then gets logged by the next create. Now you've told the dev exactly where to go find the spot where they got your object but didn't dispose it.

Another place is when you are calling something that has an unmanaged resource behind it along with other code that isn't behaving. For example, you are writing a web part in SharePoint that is calling new SPSite and OpenWeb... perhaps you are being a good SPRequest citizen, but another web part on the site that you didn't write isn't being so nice.

You could make auto-recovery wrappers for the stuff you use. Your newSPSite method would attempt to return new SPSite but if that should fail, Collect + WFPF and try again. Ugh, what a pain. But sometimes it beats trying to explain to someone why it is another webpart's fault that your webpart explodes.

Monday, October 19, 2009 9:40:14 PM (US Mountain Standard Time, UTC-07:00)  #    Comments [0] -
.NET Internals
Comments are closed.
Archive
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
All Content © 2010, Hafthor Stefansson - Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way. - Sign In