我应该在应用程序退出之前运行Dispose吗? [英] Should I run Dispose before application exit?

查看:70
本文介绍了我应该在应用程序退出之前运行Dispose吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该在应用程序退出之前运行Dispose吗?



例如,我创建了许多对象,其中一些具有事件订阅:

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

例如,在我的工作中,我应该使用具有 IDisposable 界面。
然后,我决定关闭应用程序并执行以下操作:

  Enviroment.Exit(-1); 

对吗?



我应该对实现IDisposable接口的所有对象调用 Dispose 吗?
会发生内存泄漏吗?



P.S。这是使用WCF和MQ的服务器端应用程序。

解决方案

在这种特定于 的情况下,您可以选择不处置。我确定我能回想起雷蒙德·陈(Raymond Chen)的类比,那就是在建筑物被拆除之前不清空垃圾箱。 1



您的整个过程大约是消失。



但是,由于操作系统将要回收其所有资源,因此您无需清理内部资源。



必须对此进行权衡:a)出现非标准,b)潜在地从例如触发警告stylecop,与预期的报酬相比,花费更少的时间来退出 -您是否真的需要优化应用程序的这一部分?



曾经评论过,尽管在这种情况下可能绝对没有必要,我通常还是选择使用 c将我的一次性对象包裹起来。






1 这是一个关于在DLL_PROCESS_DETACH中不做任何事情。推理类似。


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.

解决方案

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.

这篇关于我应该在应用程序退出之前运行Dispose吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆