Reputation: 12087
I was using .NET MemoryProfiler to look for memory leaks in my app and I can't seem to figure out the pattern of when I should call Dispose() when it comes to creating and showing winforms. It seems that when I do
Form frm = new SomeForm();
frm.ShowDialog();
bool test = frm.IsDisposed()
test is "False" which is surprising to me and .NET MemoryProfiler also confirms that the form wasn't disposed of properly. I thought if I "Close (X)" the dialog then it would effectively call .Dispose() on the form but doesn't seem to be the case. I am curious what would happen if I do:
Form frm = new SomeForm();
frm.Show();
Would the form be disposed when I click the "Close (X)" button on the form? I am trying to find a rule when I should call "Dispose()" and when I don't need to call "Dispose" (because it will be disposed implicitly)...
Upvotes: 1
Views: 1358
Reputation: 2520
From MSDN: Form.Dispose Method (Boolean):
Dispose will be called automatically if the form is shown using the Show method. If another method such as ShowDialog is used, or the form is never shown at all, you must call Dispose yourself within your application.
Upvotes: 2
Reputation: 64943
When a class implements IDisposable
it means that you are forced to dispose it unless some other takes the responsibility of managing object's life-time.
In your case, your code should look like this:
using(Form frm = new SomeForm())
{
frm.ShowDialog();
}
Your "Close button" closes the whole dialog, but hidding the whole form doesn't release low-level resources used to draw and/or handle GUI.
Upvotes: 2
Reputation: 700910
Generally, you are responsible for disposing any disposable object that you create. They will not dispose themselves.
Calling a method like ShowDialog
doesn't dispose the object, even if it seems like a one-off operation. Even if you aren't going to use the object again, there might be information in it that you want to use after the user has closed it.
Calling the Show
method is however a different matter. Once you have shown the form it will live until it is closed, and will actually dispose itself.
Upvotes: 4