TPL和异常处理

Moo*_*ght 8 c# continuations exception-handling task-parallel-library

总而言之,对于上述主题存在许多疑问,但我认为这有足够的不同以保证一个新问题.我有以下Task和继续处理各种任务Status; TaskStatus.RanToCompletion,TaskStatus.Canceled和当然的AggregateException通过TaskStatus.Faulted.代码看起来像

Task<bool> asyncTask = Task.Factory.StartNew<bool>(() =>
    asyncMethod(uiScheduler, token, someBoolean), token);

asyncTask.ContinueWith(task =>
{
    // Check task status.
    switch (task.Status)
    {
        // Handle any exceptions to prevent UnobservedTaskException.             
        case TaskStatus.RanToCompletion:
            if (asyncTask.Result)
            {
                // Do stuff...
            }
            break;
        case TaskStatus.Faulted:
            if (task.Exception != null)
                mainForm.progressRightLabelText = task.Exception.InnerException.Message;
            else
                mainForm.progressRightLabelText = "Operation failed!";
        default:
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这一切都运作良好,但我担心我是否正确这样做,因为有可能AggregateException从延续中被抛出 - 那么呢?

我不想继续WaitasyncTask的延续,因为这将阻止返回UI线程.捕捉从延续中抛出的任何异常并不意味着我必须做这样的事情

Task parentTask = Task.Factory.startNew(() => 
    {
        Task<bool> asyncTask = Task.Factory.StartNew<bool>(() =>
            asyncMethod(uiScheduler, token, someBoolean), token);

        Task continueTask = asyncTask.ContinueWith(task =>
            {
                // My continuation stuff...   
            }

        try
        {
            continueTask.Wait();
        }
        catch(AggregateException aggEx)
        { 
            // Some handling here...
        }
    });
Run Code Online (Sandbox Code Playgroud)

这会工作吗?这里的最佳做法是什么?

一如既往,谢谢你的时间.

Dre*_*rsh 12

可以在您的代表中查看传统的try/catch,AggregateException或者您可以链接特定的延续,只有在使用该TaskContinuationOptions.OnlyOnFaulted选项的前提时才会运行.后一种方法允许定义非常干净的任务工作流程.例如:

Task myRootTask = ....;

myRootTask.ContinueWith(rootAntecdent =>
{
    // this will only be executed if the antecedent completed successfully, no need to check for faults
},
TaskContinuationOptions.OnlyOnRanToCompletion);

myRootTask.ContinueWith(rootAntecedent =>
{
    // this will only be executed if the antecedent faulted, observe exception and handle accordingly
},
TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)