问题
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