11

有多种方法可以观察任务中引发的异常。其中之一在带有 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 后才会观察到?

4

2 回答 2

10

一旦您访问该属性,它们就会被视为观察到的。Exception

另请参阅AggregateException.Handle。您可以t.Exception.Handle改用:

t.Exception.Handle(exception =>
            {
            Console.WriteLine(exception);
            return true;
            }
    );
于 2012-07-31T15:52:50.007 回答
2

样本

Task.Factory.StartNew(testMethod).ContinueWith(p =>
            {
                if (p.Exception != null)
                    p.Exception.Handle(x =>
                        {
                            Console.WriteLine(x.Message);
                            return false;
                        });
            });
于 2013-06-04T14:47:56.263 回答