What is happening when I close a form, which was opened using Show()
, by using Dis开发者_StackOverflow社区pose()
instead of Close()
? Can someone tell me in detail, what happening in the Dispose()
method?
The basic difference between Close()
and Dispose()
is, when a Close()
method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose()
method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.
Or just a general statement. With the connection object calling Close()
will release the connection back into the pool. Calling Dispose()
will call Close()
and then set the connection string to null.
Some objects such as a Stream implement IDisposable
but the Dispose method is only available if you cast the object to an IDisposable
first. It does expose a Close()
method though.
I would always argue that you should call Dispose()
on any object that implements IDisposable
when you are through with the object. Even if it does nothing. The jit compiler will optimize it out of the final code anyway. If the object contains a Close()
but no Dispose()
then call Close()
.
You can also use the using statement on IDispoable
objects
using(SqlConnection con = new SqlConnection())
{
//code...
}
This will call Dispose()
on the SqlConnection when the block is exited.
Decompiling the two methods (Dispose
and Close
) it turns out that the latter performs two additional checks and then calls Dispose
, just like this:
object[] objArray;
if (base.GetState(262144))
{
throw new InvalidOperationException(SR.GetString("ClosingWhileCreatingHandle", new object[] { "Close" }));
}
if (base.IsHandleCreated)
{
this.closeReason = CloseReason.UserClosing;
base.SendMessage(16, 0, 0);
return;
}
base.Dispose();
From documentation:
When a form is closed, all resources created within the object are closed and the form is disposed. [...] The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.
Hope it helps.
Actually, in this case Close()
and Dispose()
is quite different:
Close
closes the form by sending the appropiate Windows message. You will be able to open the form again using Open()
Dispose
disposes the form resources altogether, and you won't be able to re-use the form instance again.
精彩评论