What is happening when I close a form, which was opened using Show()
, by using Dispose()
instead of Close()
? Can someone tell me in detail, what happening in the Dispose()
method?
Net documentation for the OleDbCommand, Close() closes the connection and returns it to the connection pool, and Dispose() closes the connection and REMOVES it from the connection pool.
Form. Close() sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.
The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
Implement a finalizer to free resources when Dispose is not called. By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With