我想让用户能够取消正在运行的查询。查询真的很慢。 (查询优化不是重点。)这主要是出于我的好奇心。
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 中取消这么长的查询?
最佳答案
如果您真的绝对想彻底杀死它,请使用此方法:
- 在开始长时间运行的查询之前通过调用
SELECT @@SPID AS 'SESSIONID'
存储 session ID在同一个连接上
当你想杀死它时:
- 打开一个新的数据库连接
- 发出
KILL
该 session ID 的命令
请注意,MSDN 文档指出您需要权限ALTER ANY CONNECTION
才能执行此操作
关于c# - sql server 查询真的可以被取消/杀死吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7837739/