c# - 在任务中捕获异常的最佳方法是什么?

标签 c# .net 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
             */

        });        
    }
}

最佳答案

有两种方法可以做到这一点,具体取决于您使用的语言版本。

C# 5.0 及以上

您可以使用 asyncawait关键字来为您简化这方面的工作。

asyncawait 被引入到语言中以简化 Task Parallel Library 的使用,使您不必使用 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.
}

请注意,封装上述方法的方法必须使用async关键字,这样您就可以使用await

C# 4.0 及以下

您可以使用 ContinueWith overload 处理异常从 TaskContinuationOptions enumeration 中获取一个值,像这样:

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

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

TaskContinuationOptions 枚举的 OnlyOnFaulted 成员表示如果前面的任务抛出异常,应该执行延续。

当然,您可以多次调用 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();

关于c# - 在任务中捕获异常的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980712/

相关文章:

c# - 新线程的开始选项卡,关闭选项卡和结束线程

.net - CopyPixelOperation.SourceInvert 不起作用

c# - 任务构造函数中的取消标记 : why?

c# - 显示从 MySQL 填充数据集的进度

c# - 返回 Timer 的处理方法

c# - 选择表的列名和类型

c# - 我如何检测我的显示器现在设置的来源?

c# - ServiceStack:如何处理错误?

c# - 为什么 Task.WaitAll() 不会在此处阻塞或导致死锁?

c# - 如何使用 c#.net 4.0 在最大定义的并行线程中运行任务