Thursday, 18 February 2010

Explicitly Call Dispose or Close on Resources You Open

If you use objects that implement the IDisposable interface, make sure you call the Dispose method of the object or the Close method if one is provided. Failing to call Close or Dispose prolongs the life of the object in memory long after the client stops using it. This defers the cleanup and can contribute to memory pressure. Database connection and files are examples of shared resources that should be explicitly closed. The finally clause of the try/finally block is a good place to ensure that the Close or Dispose method of the object is called.

Try
conn.Open()
…Finally
If Not(conn Is Nothing) Then
conn.Close()
End If
End Try

In Visual C#®, you can wrap resources that should be disposed, by using a using block. When the using block completes, Dispose is called on the object listed in the brackets on the using statement. The following code fragment shows how you can wrap resources that should be disposed by using a using block.

SqlConnection conn = new SqlConnection(connString);
using (conn)
{
conn.Open();
. . .
} // Dispose is automatically called on the connection object conn here.

No comments:

Post a Comment