我有一个长时间运行的操作,我正在使用TPL在后台线程上。我目前的工作,但我很困惑,我应该在取消请求期间处理我的AggregateException
。如何正确取消TPL任务(续)
在按钮单击事件,我开始我的过程:
private void button1_Click(object sender, EventArgs e)
{
Utils.ShowWaitCursor();
buttonCancel.Enabled = buttonCancel.Visible = true;
try
{
// Thread cancellation.
cancelSource = new CancellationTokenSource();
token = cancelSource.Token;
// Get the database names.
string strDbA = textBox1.Text;
string strDbB = textBox2.Text;
// Start duplication on seperate thread.
asyncDupSqlProcs =
new Task<bool>(state =>
UtilsDB.DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB),
"Duplicating SQL Proceedures");
asyncDupSqlProcs.Start();
//TaskScheduler uiThread = TaskScheduler.FromCurrentSynchronizationContext();
asyncDupSqlProcs.ContinueWith(task =>
{
switch (task.Status)
{
// Handle any exceptions to prevent UnobservedTaskException.
case TaskStatus.Faulted:
Utils.ShowDefaultCursor();
break;
case TaskStatus.RanToCompletion:
if (asyncDupSqlProcs.Result)
{
Utils.ShowDefaultCursor();
Utils.InfoMsg(String.Format(
"SQL stored procedures and functions successfully copied from '{0}' to '{1}'.",
strDbA, strDbB));
}
break;
case TaskStatus.Canceled:
Utils.ShowDefaultCursor();
Utils.InfoMsg("Copy cancelled at users request.");
break;
default:
Utils.ShowDefaultCursor();
break;
}
}, TaskScheduler.FromCurrentSynchronizationContext()); // Or uiThread.
return;
}
catch (Exception)
{
// Do stuff...
}
}
在该方法中DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true)
我
DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true)
{
try
{
for (int i = 0; i < someSmallInt; i++)
{
for (int j = 0; j < someBigInt; j++)
{
// Some cool stuff...
}
if (_token.IsCancellationRequested)
_token.ThrowIfCancellationRequested();
}
}
catch (AggregateException aggEx)
{
if (aggEx.InnerException is OperationCanceledException)
Utils.InfoMsg("Copy operation cancelled at users request.");
return false;
}
catch (OperationCanceledException)
{
Utils.InfoMsg("Copy operation cancelled at users request.");
return false;
}
}
在按钮的Click事件(或使用delegate
(buttonCancel.Click + =代理{/ 取消任务 /} ) I cancel the
任务如下:
private void buttonCancel_Click(object sender, EventArgs e)
{
try
{
cancelSource.Cancel();
asyncDupSqlProcs.Wait();
}
catch (AggregateException aggEx)
{
if (aggEx.InnerException is OperationCanceledException)
Utils.InfoMsg("Copy cancelled at users request.");
}
}
这样捕获OperationCanceledException
罚款方法DuplicateSqlProcsFrom
并打印我的消息,但在asyncDupSqlProcs.ContinueWith(task => { ... });
提供的回拨提供task.Status
以上总是RanToCompletion
;它应该被取消!
在这种情况下捕获和处理Cancel()
任务的正确方法是什么?我知道如何在this example from the CodeProject和examples on MSDN中显示的简单情况下完成这项工作,但在运行延续时我很困惑。
在这种情况下如何捕获取消任务以及如何确保task.Status
得到正确处理?
谢谢你。它真的有帮助。我已经到了从'DuplicateSqlProcsFrom'方法中删除handeling的阶段,但仍然试图在其他地方捕获它。 – MoonKnight 2012-03-13 13:59:25
我按照你的建议完成了,但在我的延续方法中,我只能得到'TaskStatus.Faulted'条件,从来没有'TaskStatus.Cancelled'。你知道这可能是为什么吗? – MoonKnight 2012-03-13 14:12:49
我已经为此答案添加了解释和解决方案。 – shambulator 2012-03-13 15:18:37