Managing Resources in .NET

A simple tip for managing your resources smartly with 'using'

using (SqlConnection sqlConn =
   new SqlConnection(...))
{
   sqlConn.Open();
   using (SqlCommand sqlCmd =
          new SqlCommand(..., sqlConn))
   {
      using (SqlDataReader dr = cmd.ExecuteReader())
      {
         // Access elements items here
      }
   }
}

Extract from MSDN:
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

Published Thursday, August 16, 2007 12:11 AM by microlau
Filed under:

Comments

# re: Managing Resources in .NET

Friday, August 17, 2007 4:32 PM by hannes

This is a good tip - always use it (for anything that implements IDisposable).

If you don't use it for opening a connection, for example, and your code throws an exception (and you dont close the connection in an exception handler), then that connection remains there until the garbage collector comes along... and I've seen that cause the connection pool to run out.