一次性处置依赖性与Windows桌面应用程序 [英] Disposing disposable dependencies with Windows desktop applications

查看:152
本文介绍了一次性处置依赖性与Windows桌面应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,我们应该处理处置的对象,一旦我们使用他们已经完成。现在的问题是:如果我有一个一次性的对象(如数据库上下文)被整个Windows桌面应用程序的整个生命周期中使用(如WPF或WinForms的):我应该部署在应用程序关闭事件的对象(为什么,当,当不)?

We all know that we should dispose of disposable objects once we have finished using them. The question is: If I have a disposable object (eg. a database context) being used throughout the entire lifetime of a windows desktop application (e.g. WPF or WinForms): Should I dispose of that object in the application shutdown event (why, when, when not)?

推荐答案

作为一项规则,你应该避免住你的应用程序的生命周期处置的对象。许多对象,诸如数据库的上下文,只是不应的被使用在该范围内。

As a rule, you should avoid having disposable objects that live for the lifetime of your application. Many objects, such as database contexts, just shouldn't be used at that scope.

如果你确实需要,虽然做到这一点,这取决于是否不是对象正确地实现了IDisposable模式。如果一次性对象实现终结那么当应用程序结束,即使你不叫处置就可以了它会被处置。如果对象没有实现一个终结,你需要处理它,当应用程序被关闭,除非它会泄漏的资源是一个不是问题的问题。例如,它是否会被泄露,将被关闭,当过程结束的内存,就没有必要将其释放,如果只打算从事件退订没有必要为它运行等,如果您不确定什么样的完全的被释放在处置方法,那么你应该是安全的,反正调用它。

If you really do need to do it though, it depends on whether or not the object "properly" implements the IDisposable pattern. If the disposable object implements a finalizer then it will be disposed when the application ends even if you don't call Dispose on it. If the object doesn't implement a finalizer you will need to dispose of it when the application is shutting down unless the resource that it would leak is a non-issue. For example, if it would be leaking memory that will be shut down when the process ends, there's no need to release it, if it is only going to be unsubscribing from events there's no need for it to run, etc. If you are unsure of what exactly is being released in the Dispose method then you should be safe and call it anyway.

这篇关于一次性处置依赖性与Windows桌面应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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