简体   繁体   English

TaskContinuationOptions.OnlyOnFaulted 被忽略

[英]TaskContinuationOptions.OnlyOnFaulted is being ignored

I am using the Task Parallel Library for .NET 3.5 (a NuGet package ).我正在使用 .NET 3.5 的任务并行库(一个NuGet 包)。

When running the following code, the OnlyOnFaulted task is not being run when an exception is thrown from MethodThrowsException() :运行以下代码时,如果从OnlyOnFaulted MethodThrowsException()抛出异常,则不会运行OnlyOnFaulted任务:

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

I (eventually) get this exception:我(最终)得到这个例外:

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

AggregateException 未处理

I cannot see where it is located as it is being thrown within System.Threading.dll (I would need to load the pdb).我看不到它所在的位置,因为它是在 System.Threading.dll 中抛出的(我需要加载 pdb)。

As far as I can see, I am observing the exception correctly, as specified by this MSDN article .据我所知,我正确地观察到异常,正如这篇 MSDN 文章所指定的那样。

So I know this question is pretty old, but I encountered this same problem today, and this question was the only one that I could find related to this issue on StackOverflow.所以我知道这个问题已经很老了,但我今天遇到了同样的问题,这个问题是我在 StackOverflow 上唯一能找到的与这个问题相关的问题。 I'm going to add my solution in hopes it helps someone else in the same situation.我将添加我的解决方案,希望它可以帮助处于相同情况的其他人。

The problem here is that the thrown exception is not actually being handled by the continuation.这里的问题是抛出的异常实际上并没有被延续处理 The exception(s) thrown within the task remain unhandled individually, therefore we must actually handle them.任务中抛出的异常仍未单独处理,因此我们必须实际处理它们。 Include the code below inside the continuation and it should resolve the issue:在延续中包含以下代码,它应该可以解决问题:

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

}, TaskContinuationOptions.OnlyOnFaulted);

More information here at the MSDN documentation .更多信息请参见 MSDN 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM