在Task中捕获异常的最佳方法是什么?

JiB*_*evé 68 .net c# task-parallel-library

有了System.Threading.Tasks.Task<TResult>,我必须管理可能抛出的异常.我正在寻找最好的方法.到目前为止,我已经创建了一个基类来管理调用中的所有未捕获的异常.ContinueWith(...)

我想知道是否有更好的方法可以做到这一点.或者即使这是一个很好的方法.

public class BaseClass
{
    protected void ExecuteIfTaskIsNotFaulted<T>(Task<T> e, Action action)
    {
        if (!e.IsFaulted) { action(); }
        else
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                /* I display a window explaining the error in the GUI 
                 * and I log the error.
                 */
                this.Handle.Error(e.Exception);
            }));            
        }
    }
}   

public class ChildClass : BaseClass
{
    public void DoItInAThread()
    {
        var context = TaskScheduler.FromCurrentSynchronizationContext();
        Task.Factory.StartNew<StateObject>(() => this.Action())
                    .ContinueWith(e => this.ContinuedAction(e), context);
    }

    private void ContinuedAction(Task<StateObject> e)
    {
        this.ExecuteIfTaskIsNotFaulted(e, () =>
        {
            /* The action to execute 
             * I do stuff with e.Result
             */

        });        
    }
}
Run Code Online (Sandbox Code Playgroud)

cas*_*One 95

有两种方法可以执行此操作,具体取决于您使用的语言版本.

C#5.0及以上

您可以使用asyncawait关键字为您简化大量此操作.

asyncawait引入了语言使用简化任务并行库,阻止您不必使用ContinueWith,并允许你继续计划在自上而下的方式.

因此,您可以简单地使用try/catch block来捕获异常,如下所示:

try
{
    // Start the task.
    var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });

    // Await the task.
    await task;
}
catch (Exception e)
{
    // Perform cleanup here.
}
Run Code Online (Sandbox Code Playgroud)

请注意,封装上述方法必须使用已async应用的关键字,以便您可以使用await.

C#4.0及以下

您可以使用从枚举中获取值的ContinueWith重载来处理异常,如下所示:TaskContinuationOptions

// Get the task.
var task = Task.Factory.StartNew<StateObject>(() => { /* action */ });

// For error handling.
task.ContinueWith(t => { /* error handling */ }, context,
    TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)

枚举的OnlyOnFaulted成员TaskContinuationOptions指示只有在先前任务引发异常时才应执行继续.

当然,ContinueWith在处理非例外情况时,您可以多次拨打相同的前提:

// Get the task.
var task = new Task<StateObject>(() => { /* action */ });

// For error handling.
task.ContinueWith(t => { /* error handling */ }, context, 
    TaskContinuationOptions.OnlyOnFaulted);

// If it succeeded.
task.ContinueWith(t => { /* on success */ }, context,
    TaskContinuationOptions.OnlyOnRanToCompletion);

// Run task.
task.Start();
Run Code Online (Sandbox Code Playgroud)

  • @guiomie`t`*是*例外. (4认同)
  • 上下文没有定义它是什么? (2认同)

Zar*_*trA 5

您可以创建一些自定义任务工厂,它将生成嵌入了异常处理处理的任务.像这样的东西:

using System;
using System.Threading.Tasks;

class FaFTaskFactory
{
    public static Task StartNew(Action action)
    {
        return Task.Factory.StartNew(action).ContinueWith(
            c =>
            {
                AggregateException exception = c.Exception;

                // Your Exception Handling Code
            },
            TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously
        ).ContinueWith(
            c =>
            {
                // Your task accomplishing Code
            },
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously
        );
    }

    public static Task StartNew(Action action, Action<Task> exception_handler, Action<Task> completion_handler)
    {
        return Task.Factory.StartNew(action).ContinueWith(
            exception_handler,
            TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously
        ).ContinueWith(
            completion_handler,
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously
        );
    }
};
Run Code Online (Sandbox Code Playgroud)

您可以忘记在客户端代码中从此工厂生成的任务的异常处理.在此期间,您仍然可以等待完成此类任务或以Fire-For-Forget样式使用它们:

var task1 = FaFTaskFactory.StartNew( () => { throw new NullReferenceException(); } );
var task2 = FaFTaskFactory.StartNew( () => { throw new NullReferenceException(); },
                                      c => {    Console.WriteLine("Exception!"); },
                                      c => {    Console.WriteLine("Success!"  ); } );

task1.Wait(); // You can omit this
task2.Wait(); // You can omit this
Run Code Online (Sandbox Code Playgroud)

但如果说实话,我不确定你为什么要完成处理代码.无论如何,这个决定取决于您的应用程序的逻辑.