Types that use unmanaged resources must implement the Dispose () method of the IDisposable interface to precisely free system resources. NET environment, the responsibility for releasing resource code is the user of the type, not the type or system. Therefore, any time you use a type with a Dispose () method, you have the responsibility to call the Dispose () method to release the resource. The best way to ensure that a Dispose () called structure is to use a using statement or a try/finally block.
All types that contain unmanaged resources should implement the IDisposable interface, and in addition, when you forget to handle these types properly, they will create the destructor passively. If you forget to handle these objects, those non memory resources will be released at a later time when the destructor is called exactly. This allows these objects to stay in memory for longer, which can cause your application to degrade with too much system resources.
Fortunately, it is a common task for the designer of the C # language to release resources precisely. They added a keyword to make this easier.
Let's say you wrote the following code:
public void ExecuteCommand( string connString,
string commandString )
{
SqlConnection myConnection = new SqlConnection( connString );
SqlCommand mySqlCommand = new SqlCommand( commandString,
myConnection );
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
Two of the processing objects in this example are not properly released: SqlConnection and SqlCommand. Two objects are stored in memory at the same time until the destructor is invoked. (These two classes are inherited from System.ComponentModel.Component.) )
The solution to this problem is to call their dispose after using the commands and links:
public void ExecuteCommand( string connString,
string commandString )
{
SqlConnection myConnection = new SqlConnection( connString );
SqlCommand mySqlCommand = new SqlCommand( commandString,
myConnection );
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
mySqlCommand.Dispose( );
myConnection.Dispose( );
}
This is fine, and your Dispose () call will never succeed unless the SQL command throws an exception at execution time. The using statement can ensure that the Dispose () method is invoked. When you assign objects to a using statement, the C # compiler puts these objects in a try/finally block:
public void ExecuteCommand( string connString,
string commandString )
{
using ( SqlConnection myConnection = new
SqlConnection( connString ))
{
using ( SqlCommand mySqlCommand = new
SqlCommand( commandString,
myConnection ))
{
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
}
}