【发布时间】:2014-07-02 10:05:58
【问题描述】:
如果您推荐使用 SqlCommand.Cancel(),请给出一个工作示例!
我需要在查询执行期间显示一个带有取消按钮的等待表单(如果用户单击此按钮,则查询必须停止运行)。
我的解决方案: (.net 4)
我向表单构造函数传递了两个参数:
- 查询执行任务
- 取消操作
下面是我的加载表单代码:
public partial class LoadingFrm : Form
{
//task for execute query
private Task execute;
//action for cancelling task
private Action cancel;
public LoadingFrm(Task e, Action c)
{
execute = e;
cancel = c;
InitializeComponent();
this.cancelBtn.Click += this.cancelBtn_Click;
this.FormBorderStyle = FormBorderStyle.None;
this.Load += (s, ea) =>
{
//start task
this.execute.Start();
//close form after execution of task
this.execute.ContinueWith((t) =>
{
if (this.InvokeRequired)
{
Invoke((MethodInvoker)this.Close);
}
else this.Close();
});
};
}
//event handler of cancel button
private void cancelBtn_Click(object sender, EventArgs e)
{
cancel();
}
}
下面是我的 ExecuteHelper 类的代码:
public class ExecuteHelper
{
public static SqlDataReader Execute(SqlCommand command)
{
var cts = new CancellationTokenSource();
var cToken = cts.Token;
cToken.Register(() => { command.Cancel(); });
Task<SqlDataReader> executeQuery = new Task<SqlDataReader>(command.ExecuteReader, cToken);
//create a form with execute task and action for cancel task if user click on button
LoadingFrm _lFrm = new LoadingFrm(executeQuery, () => { cts.Cancel(); });
_lFrm.ShowDialog();
SqlDataReader r = null;
try
{
//(1) here
r = executeQuery.Result;
}
catch (AggregateException ae)
{
}
catch (Exception ex)
{
}
return r;
}
}
但我无法停止执行SqlCommand。经过一段时间调用ExecuteHelper.Execute(command) 的方法从sql server 中获得带有数据的结果(SqlDataReader)?为什么?有人可以帮忙吗?如何取消执行 sqlcommand?
我还有一个问题。为什么如果我单击表单的取消按钮并且 cts.Cancel() 被称为//(1) here 我得到executeQuery.IsCanceled = false 尽管executeQuery.Status = Faulted.
【问题讨论】:
-
@Liath,因为该链接无法帮助我解决问题
-
@Liath,你可以给出工作代码,通过 SqlCommand 的 Cancel 方法停止执行查询?
-
我尝试了这个解决方案,没有成功。
标签: c# sql .net task sqlcommand