在ContinueWith中观察任务异常

Dav*_*New 11 .net c# parallel-processing multithreading 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);
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*hie 10

一旦您进入酒店,他们就被视为观察Exception.

另见AggregateException.Handle.你可以t.Exception.Handle改用:

t.Exception.Handle(exception =>
            {
            Console.WriteLine(exception);
            return true;
            }
    );
Run Code Online (Sandbox Code Playgroud)