Search This Blog

Tuesday, August 3, 2010

How to use dispose.. using statement

After a lot of googling and referring books i got to learn a few things about dispose
1) only unmanaged resources need to be disposed.
2) SqlConnection, sqlCommand are unmanaged resources, however data adapter and dataset are managed resources.
3) when u dispose sqlconnection object, it also closes the connection. no need to write .close explicitly.
4) No need to open and close the connection if u r using dataadpter and datsets. it does it itself.
5) u need to implement the Idisposable interface in your class (where u need to use dispose). then u need to override the dispose method (see the code snippet below)... on class level define a variable disposed, as
private bool disposed = false;

there are two dispose methods. one accepts no parameter and one accepts a bool parameter. to dispose an object u need to call the dispose method which doesnot have any parameter.
this.dispose()
generally this statement is written in finally block to ensure it is always executed.
 u can use dispose method in follwing way :-
public void Dispose()
{
 this.Dispose(true);
GC.SuppressFinalize(this);
}
///<summary>
/// Free managed and/or unmanaged resources used in this Class.
/// </summary>
/// <param name="disposing">true signifies that the user called the dispose, false
/// signifies the GC triggered the dispose.</param>
///
private void Dispose(bool disposing)
{
 // Check we haven't already disposed.
 if (!this.disposed)
{
 // User triggered the cleanup so Dispose managed resources here.
 if (disposing)
{
this.Dispose();
 }
 // Dispose unmanaged resources here.
SqlConnection.dispose();
 }
this.disposed = true;
}
~Classdestructor()
{
 this.Dispose(false);
}
 
However, it creates a lot of mess in the code. If u just need to dispose the sqlconnection object you can easily use the using clause. I guess its only available in C#, please check if u r using VB.NET.
Example:-
 
public DataTable getData()
{
using (SqlConnection SqlCon = new SqlConnection(connectionString))
{
SqlCommand command= new SqlCommand("StoredProcedureName", SqlCon);
command.CommandType = CommandType.StoredProcedure;
///your code code

return dataTable
}
}
 
the using block ensures that the sqlconnection object is disposed properly once it goes out of it. And it makes he code easy to understand also :)

No comments:

Post a Comment