Connection Usage Patterns
Irrespective of the .NET data provider you use, you must always:
- Open a database connection as late as possible.
- Use the connection for as short a period as possible.
- Close the connection as soon as possible. The connection is not returned to the pool until it is closed through either the Close or Dispose method. You should also close a connection even if you detect that it has entered the broken state. This ensures that it is returned to the pool and marked as invalid. The object pooler periodically scans the pool, looking for objects that have been marked as invalid.
To guarantee that the connection is closed before a method returns, consider one of the approaches illustrated in the two code samples that follow. The first uses a finally block. The second uses a C# using statement, which ensures that an object's Dispose method is called.
The following code ensures that a finally block closes the connection. Note that this approach works for both Visual Basic .NET and C# because Visual Basic .NET supports structured exception handling.
public void DoSomeWork(){ SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("CommandProc", conn ); cmd.CommandType = CommandType.StoredProcedure; try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { // Handle and log error }
Comments
Join the conversation! Your thoughts help the community grow.