Monday, April 13, 2009

Use of "Using" Keyword

Hi Friends,

We often face some problems with disposing connection, adapter and command objects.
But we can avoid such kind of situations by modifying some process logic. We can use "Using" keywords which will dispose the object which it contains.

It will work just like method block, means when method goes out of scope all object inside it will be prompted to Garbage Collector, here also those objects will be disposed after "Using" statement.

Introduction


This example demonstrates use of "Using" keyword which disposes all resources used inside it and in Data Access base classes we don't have to worried about connection and adapter dispose, they will be disposed automatically immediatly after use..

internal DataTable GetNetworkSettingsByNetworkID(int networkID)
{
try
{
using (Connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
command.CommandText = SQL_GET_NETWORKSETTINGS_BY_NETWORKID;
command.CommandType = CommandType.StoredProcedure;
command.Connection = Connection;
command.Parameters.Add(new MySqlParameter("?_NetworkID", MySqlDbType.Int32));
command.Parameters[0].Value = networkID;
using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command))
{
using (DataTable dtNetworkSettings = new DataTable())
{
dataAdapter.Fill(dtNetworkSettings);
return dtNetworkSettings;
}
}
}
}
}
catch (Exception ex)
{
PacketUtils.WriteLogError(ex, "NetworkDA::GetNetworkSettingsByNetworkID");
throw ex;
}
finally
{
if (Connection != null)
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
Connection.Dispose();
}
}
}


So always use the practice of using "Using" keywords for those objects which implements IDisposable interface.

No comments:

Post a Comment

There was an error in this gadget

Followers

My Google Reader