Jon Skeet said:
Anyone have appropriate experience which would allow them to easily
test this? While I have SQL Server on my laptop, I'm not convinced I
would know how to really *reliably* test this. I'll have a go though
I've had a go, and it seems to be false. Here's my test code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
class Test
{
static void Main()
{
OpenAndCloseConnection();
OpenAndCloseConnection();
OpenAndCloseConnection();
Console.WriteLine ("Finished opening and closing");
Console.ReadLine();
OpenAndDisposeConnection();
OpenAndDisposeConnection();
OpenAndDisposeConnection();
Console.WriteLine ("Finished opening and disposing");
Console.ReadLine();
}
static void OpenAndCloseConnection()
{
SqlConnection conn = new SqlConnection
("Server=treebeard;Integrated Security=SSPI;Database=Northwind");
conn.Open();
SqlCommand cmd = new SqlCommand
("SELECT COUNT(*) FROM REGION");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
static void OpenAndDisposeConnection()
{
SqlConnection conn = new SqlConnection
("Server=treebeard;Integrated Security=SSPI;Database=Northwind");
conn.Open();
SqlCommand cmd = new SqlCommand
("SELECT COUNT(*) FROM REGION");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Dispose();
}
}
And here's what I saw in my profiler:
Audit Login
RPC:Completed - exec sp_reset_connection
SQL:BatchCompleted - SELECT COUNT(*) FROM REGION
Audit Login
RPC:Completed - exec sp_reset_connection
SQL:BatchCompleted - SELECT COUNT(*) FROM REGION
RPC:Completed - exec sp_reset_connection
SQL:BatchCompleted - SELECT COUNT(*) FROM REGION
RPC:Completed - exec sp_reset_connection
SQL:BatchCompleted - SELECT COUNT(*) FROM REGION
RPC:Completed - exec sp_reset_connection
SQL:BatchCompleted - SELECT COUNT(*) FROM REGION
RPC:Completed - exec sp_reset_connection
SQL:BatchCompleted - SELECT COUNT(*) FROM REGION
Audit Logout
Audit Logout
The SPID was 51 except for one Login and one Logout where it was 53 - I
assume that was another connection being started in case it was needed,
although I wouldn't like to say for sure.
Anyway, I can't see any difference from the above between calling
Dispose and calling Close. Have I done something wrong, or is the idea
that Dispose removes the connection from the pool just an urban myth?