要检查超时,我相信您可以检查ex.Number的值。如果为-2,则表示超时。
-2是超时错误代码,它是从DBNETLIB(SQL Server的MDAC驱动程序)返回的。可以通过下载Reflector并在System.Data.SqlClient.TdsEnums下查找TIMEOUT_EXPIRED 来看到。
您的代码将显示为:
if (ex.Number == -2)
{
//handle timeout
}
演示失败的代码:
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");
}
}