【问题标题】:TaskContinuationOptions.OnlyOnFaulted is being ignoredTaskContinuationOptions.OnlyOnFaulted 被忽略
【发布时间】:2015-02-08 20:32:32
【问题描述】:

我正在使用 .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

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

据我所知,我正确地观察到了 this MSDN article 指定的异常。

【问题讨论】:

  • 您是如何遇到异常的?这是用调试器运行的吗?
  • @theMayer:Visual Studio 2013 将异常报告为 System.Threading.dll 中未处理。添加截图。
  • 您是否打开了“仅我的代码”?如果是这样,它会将异常报告为“未处理”,因为它们不是由“您的代码”处理的。关闭此功能——它没有用。
  • 您确定不是继续导致问题吗? IE。在 ContinueWith 中的代码周围放置一个 try/catch。你能看到 AggregateException 的 InnerException 是什么吗?
  • @MattSmith:100% 正确。 ContinueWith 未在我的 UI 线程上运行,因此设置控件属性引发异常。我无法让它工作,所以我只是使用 Dispatch(呃)。谢谢

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


【解决方案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);

更多信息请访问MSDN documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2016-06-05
    • 2014-02-25
    • 2011-05-09
    • 2011-03-27
    • 2010-11-19
    • 2018-01-18
    相关资源
    最近更新 更多