Introduction
This article is to go in deep into some key features in the ADO.NET 2 which was shipped with VS 2005.
In this article, I will go through one of the key features which is Connection Pooling.
This feature is a key feature that plays an important role in the performance of most business applications or Data-driven applications.
What's Connection Pooling?
- Connection pooling is the ability to re-use your connection to the Database. This means if you enable Connection pooling in the connection object, you actually enable the re-use of the connection to more than one user.
- The connection pooling is enabled by default in the connection object. If you disable the connection pooling, this means the connection object that you create will not be re-used by any other user than those who created that object.
Shall I Enable/Disable the Connection Pool?
Let's do an example to use what the time has required if we enable/disable the connection pool in an application.
Sample 1. (Connection Pooling is enabled)
Create a console application and put the following lines of code to the Main Method.
SqlConnection testConnection = new SqlConnection(@"Data Source=(local)\SQLEXPRESS;Initial Catalog=DEMO;Integrated Security=SSPI;");
long startTicks = DateTime.Now.Ticks;
for (int i = 1; i <= 100; i++) {
testConnection.Open();
testConnection.Close();
}
long endTicks = DateTime.Now.Ticks;
Console.WriteLine("Time taken : " + (endTicks - startTicks) + " ticks.");
testConnection.Dispose();
Run the application, on my machine the difference in time is 937626 ticks.
Sample 2. (Connection Pooling is disabled)
- Just add Pooling=false in the connection string.
- Run the application, on my machine the difference in time is 3906500 ticks.
- If you measure the difference you will see the time required by disabling the connection polling is 4 times greater than using connection pooling.
- One of the good practices when using your connection object is to enclose your code by trying {..} catch {} finally {} blocks.
- On finally block you have to call Conn.Close(); or Conn.Dispose();
- Remove all resources attached to that connection.
One of you asked what the difference of calling Close or Dispose of, the answer doesn't use both of them, Dispose method actually calls the close method internally plus removes all allocated resources for that object to be garbage collected and at the same time, the underlying connection object can be pooled.
Conclusion
Use connection pooling in your applications to maximize the use of physical connection with the Database and your application.