Should I run Dispose before application exit?

拥有回忆 提交于 2020-07-22 07:42:49

问题


Shoud 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, wich implements IDisposable interface? Can a memory leak occur?

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


回答1:


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.


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



来源:https://stackoverflow.com/questions/44158438/should-i-run-dispose-before-application-exit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!