Search code examples
c#dispose

Should I run Dispose before application exit?


Should I run Dispose before application exit?

For example, I create many objects and some of they have event subscribe:

 var myObject=new MyClass();
 myObject.OnEvent+=OnEventHandle;

And, for example, at my work I should use classes with IDisposable interface. Then, I decide to close app and do this:

Enviroment.Exit(-1);

Am I right?

Should I call Dispose to all objects, which implements IDisposable interface? Can a memory leak occur?

P.S. This is server-side app, using WCF, MQ.


Solution

  • In this specific case, you may choose not to Dispose. I was sure I recollected a Raymond Chen analogy about not emptying the bins just before you have a building demolished.1

    Your entire process is about to disappear. There's no need for you to do any cleanup of internal resources, since the OS is about to reclaim all of its resources.

    However, you have to weigh this up against it a) appearing non-standard, b) potentially triggering warnings from e.g. stylecop, versus the expected reward in taking slightly less time to exit - do you really need to optimize this part of your application?

    As others have commented, I'd usually choose to still wrap my disposable objects in usings, even though it may be strictly unnecessary in this case.


    To address supercat's 2017 comment:

    Another issue is that some classes may acquire resources the OS knows nothing about (e.g. the application sent a command to some outside machine to grant exclusive access to something until further notice; if an application never calls Dispose, the remove machine will never be told to release the resource)

    Whilst this is true, there are many ways that an external machine may never receive a message telling it to release a resource, due to network failures, machine failures, etc.

    If you're dealing with distributed architectures, you have to deal with failures, and whilst yes in this case you can (and should) Dispose to try to indicate to the remote machine that you're finished with the resource, it's not going to solve all of the other issues that have to be dealt with anyway.


    1This is the one about not doing anything in DLL_PROCESS_DETACH. The reasoning is similar.