Disposing disposable dependencies with Windows desktop applications

做~自己de王妃 提交于 2019-12-13 16:44:05

问题


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)?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/14817102/disposing-disposable-dependencies-with-windows-desktop-applications

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