我有以下任务
cancelSource = new CancellationTokenSource();
token = cancelSource.Token;
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();
asyncDupSqlProcs.ContinueWith(task =>
{
switch (task.Status)
{
// Handle any exceptions to prevent UnobservedTaskException.
case TaskStatus.Faulted:
// Error-handling logic...
break;
case TaskStatus.RanToCompletion:
if (asyncDupSqlProcs.Result)
Utils.InfoMsg(String.Format(
"SQL stored procedures and functions successfully copied from '{0}' " +
"to '{1}'", strDbA, strDbB));
break;
case TaskStatus.Canceled:
Utils.InfoMsg("Copy cancelled at users request.");
break;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
在方法DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB)
中,我有标准的取消检测:
if (_token.IsCancellationRequested)
_token.ThrowIfCancellationRequested();
取消事件是主窗体上的按钮单击,在单击事件中我有:
try
{
cancelSource.Cancel();
asyncDupSqlProcs.Wait();
}
catch (AggregateException aggEx)
{
if (aggEx.InnerException is OperationCanceledException)
Utils.InfoMsg("Copy cancelled at users request.");
}
但我似乎可以捕捉到AggregateException
,我在这里做错了什么?
编辑:在方法DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB)
中我可以捕捉到,OperationCancelledException
但我对如何处理它感到困惑。我看到的所有示例都在导致取消的事件中处理 UI 线程上的“操作取消...”等的打印。捕获取消并将其传递回 UI/调用线程的最佳方法是什么?