Search code examples
c#idisposablefinalizer

C# and what not to do in a finalizer


I read something about what not to do within a C# Finalizer and for the life of me I can't find the link.

When the destructor is called, is it safe to use reference objects within that class which owns the destructor?

I believe this is what I was reading about. But if that's the case, the destructor could not call a Dispose method to clean up un-managed resources, correct?

Note: I'm aware of IDisposable and the common implementation.


Solution

  • The basic gist of the "rules" is from within a finizer you can only call objects that have a known live root (for example all static objects) and objects that don't have a live root that also derive from CriticalFinalizerObject, unless you are a CriticalFinalizerObject then you are not allowed to call other CriticalFinalizerObjects.

    Most objects in your own class the finalizer is in will likely be off limits to touch because they are not on a live root (your class is being finalized after all) and they don't inherit from CriticalFinalizerObject.

    There is a very good article "What Your Mother Never Told You About Resource Deallocation" that explains what can and can't be done during a finalizer and explains a pattern by using SafeHandle for all unmanaged resources gets rid of the need of you ever needing to write a finalizer yourself. The article is a very long read but try to read it all and understand it, it really opened my mind to everything I was doing right, and wrong, about disposing managed and unmanaged objects.

    The article goes through and describes how to use SafeHandle, (a class derived from CriticalFinalizerObject and is IDisposable) so that you never need to worry about writing your own finializer.