How to catch SQLServer timeout exceptions

后端 未结 6 2056
轮回少年
轮回少年 2020-11-27 11:32

I need to specifically catch SQL server timeout exceptions so that they can be handled differently. I know I could catch the SqlException and then check if the message stri

6条回答
  •  感动是毒
    2020-11-27 11:49

    To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation.

    -2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading Reflector, and looking under System.Data.SqlClient.TdsEnums for TIMEOUT_EXPIRED.

    Your code would read:

    if (ex.Number == -2)
    {
         //handle timeout
    }
    

    Code to demonstrate failure:

    try
    {
        SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
        sql.Open();
    
        SqlCommand cmd = sql.CreateCommand();
        cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
        cmd.ExecuteNonQuery(); // This line will timeout.
    
        cmd.Dispose();
        sql.Close();
    }
    catch (SqlException ex)
    {
        if (ex.Number == -2) {
            Console.WriteLine ("Timeout occurred");
        }
    }
    

提交回复
热议问题