.NET WinForms application not releasing components?
I'm working with a .NET 2.0 WinForms application in C#.
I noticed some开发者_JAVA百科thing that I thought to be strange during the tear down of my application. In the designer generated dispose method:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
I'm seeing a situation where it is passing in disposing = false
parameter when components
does indeed contain some items. This leads me to believe that these resources are not getting disposed correctly/released because components.Dispose();
is not getting called. Is this ever desired behavior?
Thanks.
The disposing
parameter will be passed as false if Dispose(bool)
is being called from the finalizer. Typically this occurs when Dispose()
hasn't been called.
The Dispose(bool)
method isn't actually part of IDisposable; it's used by both IDisposable.Dispose()
and by Object.Finalize()
. The convention is that IDisposable.Dispose()
will call Dispose(true)
and Object.Finalize()
will call Dipose(false)
.
Maybe your class needs to dispose of unmanaged resources and therefor implements a finalizer as well?
Something like this:
~MyForm()
{
this.Dispose(false);
}
If Dispose(false)
is called during finalization that is fine by itself. If the Form is being finalized the contained Controls will also be on the finalization queue and calling Dispose() on them is at least superfluous.
But the fact that a Form is being finalized means that no deterministic Dispose() was called on it, and that by itself should be investigated. Unless this happens when the App is closing, as you state. Then it is harmless.
精彩评论