更新时间:2023-08-23 14:30:40
要检查超时,我相信您检查 ex.Number 的值.如果它是-2,那么你有一个超时情况.
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 是超时的错误代码,从 SQL Server 的 MDAC 驱动程序 DBNETLIB 返回.这可以通过下载 Reflector 并在 System.Data.SqlClient.TdsEnums 下查看来查看对于 TIMEOUT_EXPIRED.
-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.
您的代码将显示为:
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");
}
}