Possible Duplicate:
Entity framework 4 not closing connection in sql server 2005 profiler
Well, lots of developers on stackoverflow are saying that I should not worry to close my connection: my using statement will close the connection for me, here and here and all over the site. Unfortunately, I do not see it happening. Here is my code:
[Test, Explicit]
public void ReconnectTest()
{
const string connString = "Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;Application Name=ReconnectTest;";
for (int i = 0; i < 2000; i++)
{
try
{
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT 1 as a";
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
//conn.Close();
// optional breakpoint 1 below
}
}
catch(SqlException e)
{
// breakpoint 2 below
Console.WriteLine(e);
}
// breakpoint 3 below
}
}
When I enable all breakpoints and start my test, the first iteration succeeds, and I hit breakpoint 3. At this point, the connection is still open: I see it in the Profiler, and sp_who2 outputs it too.
Let's suppose that at this time I am out for a lunch, and my connection is idle. As such, our production server kills it. To imitate it, I am killing the connection from SSMS.
So, when I hit F5 and run the second iteration, my connection is killed. Unfortunately, it does not reopen automatically, so ExecuteNonQuery throws the following exception: "transport-level error has occurred". When I run the third iteration, my connection actually opens: I see it as an event in Profiler, and sp_who2 outputs it as well.
Even when I have uncommented my conn.Close() command, the connection still does not close, and when I kill it from SSMS, the next iteration still blows up.
What am I missing? Why can't using statement close my connection? Why can't Open() actually open it the first time, but succeeds the next time?
This question has originated from my previous one