要判断超时,我相信您需要判断ex.Number的值.如果是-2,则会出现超时情况.
是从-2\f25 DBNETLIB-2\f6(SQL Server的-2\f25 MDAC-2\f6驱动程序)返回的超时错误代码.这可以通过下载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");
}
}