在ContinueWith中观察任务异常

时间:2012-07-31 15:34:34

标签: c# .net multithreading parallel-processing task-parallel-library

有多种方法可以观察任务中抛出的异常。其中一个是带有OnlyOnFaulted的ContinueWith:

var task = Task.Factory.StartNew(() =>
{
    // Throws an exception 
    // (possibly from within another task spawned from within this task)
});

var failureTask = task.ContinueWith((t) =>
{
    // Flatten and loop (since there could have been multiple tasks)
    foreach (var ex in t.Exception.Flatten().InnerExceptions)
        Console.WriteLine(ex.Message);
}, TaskContinuationOptions.OnlyOnFaulted);

我的问题:一旦failureTask开始,是否会自动观察异常,或者只有在我触摸'ex.Message后才会观察到异常?

2 个答案:

答案 0 :(得分:10)

访问Exception媒体资源后,系统会将其视为观察

另见AggregateException.Handle。您可以改为使用t.Exception.Handle

t.Exception.Handle(exception =>
            {
            Console.WriteLine(exception);
            return true;
            }
    );

答案 1 :(得分:2)

样本

Task.Factory.StartNew(testMethod).ContinueWith(p =>
            {
                if (p.Exception != null)
                    p.Exception.Handle(x =>
                        {
                            Console.WriteLine(x.Message);
                            return false;
                        });
            });
相关问题