Tuesday, March 8, 2011

System.Data.SqlClient.SqlException: Timeout expired

You are most likely getting this because you are leaking connections, a good rule to follow is borrowed from Angel Saenz-Badillos: blog post.

public void DoesNotLeakConnections()
{
     Using (SqlConnection sqlconnection1 = new SqlConnection("Server=.\\SQLEXPRESS ;Integrated security=sspi;connection timeout=5"))
     {
          sqlconnection1.Open();
          SqlCommand sqlcommand1 = s          qlconnection1.CreateCommand();
          sqlcommand1.CommandText = "raiserror ('This is a fake exception', 17,1)";
          sqlcommand1.ExecuteNonQuery(); //this throws a SqlException every time it is called.     sql     connection1.Close(); //Still never gets called.     }// Here sqlconnection1.Dispose is _guaranteed_}