我正在尝试更改 SqlCommand 查询的超时,方法是测试我对给定连接字符串的连接。代码类似这样:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT ...", connection);
cmd.CommandTimeout = 10;
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
connection.Close();
}
我想在这里有一个短暂的超时,因为我只是想测试这个连接字符串是否正常。 但是,无论我在 CommandTimeout 上设置什么数字(我试过 0、1、2、4、10、30、60、120),我为虚拟连接字符串获得的实际时间总是大致相同(总运行时间约为15 秒)。
所以,在我看来,由于某种原因,我在 CommandTimeout 上设置的值被忽略了。
有什么想法吗?
最佳答案
我认为您混淆了 SqlCommand.CommandTimeout
的确切用途。根据 this MSDN reference :
Gets or sets the wait time before terminating the attempt to execute a command and generating an error.
在您的例子中,您正在执行一个 DataReader 并单步执行您的查询(无论它是什么)。每个 Read()
花费的时间最少,这就是您不会达到超时的原因。
编辑:
如果您使用了错误的连接字符串,您的Timeout
将不是命令超时,而是连接时间。默认为 15 秒。这是对您的情况有效的超时。
您将在方法调用 SqlConnection.Open()
上超时,而不是 SqlCommand.ExecuteReader()
。因此 ConnectionTimeout
属性将成为有效的超时值。
关于c# - 命令超时不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9432409/