I have several objects in our framework, that by the requirement need to provide event ObjectTerminated. The user of the framework can subscribe to this event and clean-up some unmanaged stuff, that he is using. These objects are designed to exist the whole life time of the application, and I’m not controlling their life. You can think of them as an array of singletons.
I want to write code like this:
class SomeWorkflowControlObject
{
public event EventHandler<> ObjectTerminated;
~SomeWorkflowControlObject()
{
if (ObjectTerminated != null) ObjectTerminated(this, null);
}
}
I am not sure, am I allowed to do that. What could go possibly wrong with such solution?
Updated:
What about Process.GetCurrentProcess().Exited ? Can I use it in such manner?
You should not do this. Basically, destructors do not exist in C#. What you have written is a finalizer, and the only thing a finalizer should ever do is to free unmanaged resources.
You are not allowed to access any other managed object at all, since the garbage collector might already have removed it. I do not think your
nullcheck is a sufficient guard against this situation; that object reference might still point to your (event) delegate, even if it’s already gone.So in short, don’t do this.
Alternatives:
Subscribe to the
Application.ApplicationExitevent if you have a Windows Forms application.You might want to consider implementing the
IDisposableinterface instead and then do something like this:Take note that even in the case of using
IDisposable, it’s probably not a good idea / design to trigger an event inside the object that is getting disposed, since disposed objects should no longer be accessed.For this very reason, I would recommend you do the following:
Use a
try…finallyblock:This would seem best to me because you are not abusing the
IDisposableinterface, and it’s very clear what the code does… there’s no hidden meaning.