正在忽略TaskContinuationOptions.OnlyOnFaulted

时间:2014-12-10 15:17:25

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

我正在使用.NET 3.5的任务并行库(一个NuGet package)。

运行以下代码时,OnlyOnFaulted抛出异常时未运行MethodThrowsException()任务:

var task = Task.Factory.StartNew<SomeType>(() =>
{
    MethodThrowsException();
})
.ContinueWith(t =>
{
    ExceptionMessageTextBox.Text = t.Exception.Message;
},
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

我(最终)得到了这个例外:

System.AggregateException was unhandled
Message: An unhandled exception of type 'System.AggregateException' occurred in System.Threading.dll
Additional information: TaskExceptionHolder_UnhandledException

AggregateException was unhandled

我无法看到它位于System.Threading.dll中的位置(我需要加载pdb)。

据我所知,我正在按照this MSDN article的规定正确观察异常。

1 个答案:

答案 0 :(得分:-1)

所以我知道这个问题很老了,但我今天遇到了同样的问题,这个问题是我在 StackOverflow 上找到的唯一一个与此问题相关的问题。我将添加我的解决方案,希望它可以帮助处于相同情况的其他人。

这里的问题是抛出的异常实际上并没有被延续处理。任务中抛出的异常仍未单独处理,因此我们必须实际处理它们。在延续中包含以下代码,它应该可以解决问题:

backgroundTask.ContinueWith(t =>
{
    if (t.Exception != null)
    {
        var flattenedExceptions = t.Exception.Flatten();
        flattenedExceptions.Handle((exp) => {
            // process each exception here
            return true;
        });
    }

}, TaskContinuationOptions.OnlyOnFaulted);

点击 further overload of zip 了解更多信息。