c# - sql server 查询真的可以被取消/杀死吗?

标签 c# sql-server

我想让用户能够取消正在运行的查询。查询真的很慢。 (查询优化不是重点。)这主要是出于我的好奇心。

MSDN 说:

If there is nothing to cancel, nothing occurs. However, if there is a command in process, and the attempt to cancel fails, no exception is generated.

  • Cmd - SqlCommand
  • DA - 数据适配器
  • 连接 - SqlConnection
  • 当前搜索 - 主题
  • LongQuery - 单例

这是我所拥有的:

var t = new Thread(AbortThread);
t.Start();

void AbortThread()
{
    LongQuery.Current.Cmd.Cancel();
    LongQuery.Current.Cmd.Dispose();
    LongQuery.Current.DA.Dispose();
    LongQuery.Current.Conn.Close();
    LongQuery.Current.Conn.Dispose();
    LongQuery.Current.Cmd = null;
    LongQuery.Current.DA = null;
    LongQuery.Current.Conn = null;
    CurrentSearch.Abort();
    CurrentSearch.Join();
    CurrentSearch = null;
}

我注意到 CurrentSearch.Abort() 正在阻塞,这就是为什么我将它包装在一个线程中,这可能意味着该线程仍在工作。

最后,除了这个我还能做些什么来取消查询?是否真的可以从 .NET 中取消这么长的查询?

最佳答案

如果您真的绝对想彻底杀死它,请使用此方法:

当你想杀死它时:

  • 打开一个新的数据库连接
  • 发出 KILL该 session ID 的命令
    请注意,MSDN 文档指出您需要权限 ALTER ANY CONNECTION 才能执行此操作

关于c# - sql server 查询真的可以被取消/杀死吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7837739/

相关文章:

c# - Visual Studio 调试器可以显示未加引号/未转义的字符串吗?

c# - WP7 上 ListPicker 的 caliburn.micro 绑定(bind)约定

c# - Windows 窗体 - 打开新线程时如何防止 System.AccessViolationException

SQL插入不同的记录

sql - T-SQL 中 ISNULL 和 COALESCE 的区别

sql - 如何向数据库插入空值?

c# - ASP.NET Core 浏览器链接 `Unable to get property ' 文件'`

C# - 获取引用的引用

sql-server - 在哪里可以找到列数据类型的 Sql Server 元数据?

sql - 替换字符串 SQL