I am developing a pretty extensive system in .NET, which involves a lot of system programming. Most time, I'm using the IDisposable pattern to handle resource disposal, but sometimes this isn't applicable (or left out by mistake) and resource gets destroyed during Finalize(). This might happen in COM interop, or when destructor calls Dispose() and there is an exception inside of it.
Basically: it is not always possible to clearly see and handle each scenario when finalizer might throw. And when it happens, the application will most certainly crash.
The reason why I'm concerned with specifically this class of problems is that finalizers are not called by a thread that created or used an object, so it is almost impossible task to tie the exception to the context in which the object was created. All you are getting is some generic GC thread.
So, question to the public now: if you account for those kind of issues, what do you do to control them? Tag the objects? Use a 3rd party tool which allows tracking those issues?
Also: is it possible to trigger some sort of global "Finalizer threw" event, to at least log that this very problem has happened?
EDIT1: Many thanks to everyone who submitted valuable input, I think I'm somewhat clearer now on what needs to be done. Last thing I would really like to get from this discussion is if somebody knows the methodology to trigger code on exception in finalizer (even if app crash is still inevitable), so that I could at least log it, without having to modify destructor of every class.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…