4

我有以下任务

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/调用线程的最佳方法是什么?

4

2 回答 2

2

它很可能与 Visual Studio 中的“仅我的代码”模式(默认为选中)有关。调试器在 TPL 可以观察到异常之前中断。尝试取消选中该框,看看是否可以解决问题(工具->选项->调试->常规,然后取消选中该框)

于 2012-03-09T00:05:29.637 回答
1

要获得OperationCancelledException,需要使用与传递给任务构造函数的令牌相同的令牌来抛出它:

new Task<bool>(state =>
    UtilsDB.DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB),
        "Duplicating SQL Proceedures", token);
于 2012-03-15T19:53:42.027 回答