Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dispose() method instead of close() method to a form

Tags:

winforms

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?

like image 582
MaxCoder88 Avatar asked Sep 24 '11 10:09

MaxCoder88


People also ask

What is the difference between Dispose and close?

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.

Does form close call Dispose?

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.

How do you use the dispose method?

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.

What happens if Dispose is not called?

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.


1 Answers

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.

like image 187
Mitja Bonca Avatar answered Oct 01 '22 22:10

Mitja Bonca