C# - 即使 CommandTimeout 设置为在设定时间后终止查询,查询仍在 SQL Server 数据库中运行

标签 c# sql-server

在我的 C# 代码中,我使用的是 CommandTimeout函数以确保任何执行时间超过 30 秒的查询都从服务器和数据库中终止。但是,当在数据库中列出当前正在运行的查询时,设置为在 30 秒后取消的查询运行超过 30 秒

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    SqlCommand sqlCommand = new SqlCommand(query, connection);

    //Set Timeout to 30s
    sqlCommand.CommandTimeout = 30;
    SqlDataAdapter da = new SqlDataAdapter(sqlCommand);

    da.Fill(response);
    connection.Close();
    da.Dispose();
}

enter image description here

为什么查询仍在数据库中运行?我现在唯一的选择是从服务器发送另一个查询以在 30 秒后终止查询 (KILL [session_id]) 吗?

编辑:为此查询返回了 300Mb 的数据。

最佳答案

StackOverflow 上有一个 number of posts 指示 SqlCommand.CommandTimeout 不会影响 SqlDataAdapter.Fill 的行为。相反,您应该设置 SqlDataAdapter 的 SelectCommand.CommandTimeout 属性。

但是,有些 other 帖子似乎表明即使这样也行不通。特别是 This one 让我认为只有在查询开始产生结果之前发生超时时才会取消查询。一旦结果开始出现,它似乎会忽略所有超时。

我的建议是重新考虑使用 SqlDataAdapter。根据您的用例,也许像 Dapper 这样的库更适合您?

您可能还需要考虑将此作为缺陷报告给 .NET 团队。在过去报告此类错误时,我取得了不同程度的成功;这取决于团队是否要优先解决问题。

更新

正如 Marc Gravell 指出的 here ,这看起来可能是预期的、记录在案的行为。

lol: from the documentation (https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx)

For example, with a 30 second time out, if Read requires two network packets, then it has 30 seconds to read both network packets. If you call Read again, it will have another 30 seconds to read any data that it requires.

因此:此超时会在每次读取时自行重置。所以:它会绊倒的唯一方法 如果任何单个读取操作花费的时间超过 2 秒。只要 SQL Server 设法在那段时间将至少一行放到管道上: 它不会通过任何一个 API 超时。

关于C# - 即使 CommandTimeout 设置为在设定时间后终止查询,查询仍在 SQL Server 数据库中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51637025/

相关文章:

c# - 为什么YouTube的v3 API声称我的访问 token 没有插入实时流的权限?

sql - 如何使用动态 SQL 生成列组?

sql - 如何从行获取 SQL 结果 View 以分隔列

sql - 从 SQL Server 中的字符串末尾删除连字符

c# - Automapper 无法映射到 IEnumerable

c# - 最小边界四叉树节点

sql-server - 计算 SQL Server 2008 中的回滚次数

sql - 将日期格式转换为 SELECT 中的双周存储桶

c# - .Net & C# : Trying to have a transparent image on a button (assigned from IDE)

c# - 如果使用无效的泛型类型,我应该抛出异常吗?如果是,抛出哪个异常?