【问题标题】:Task Continuation (OnlyOnFaulted) still gets unobserved exception任务继续(OnlyOnFaulted)仍然得到未观察到的异常
【发布时间】:2012-09-01 20:59:13
【问题描述】:

我有一个继续处理错误的任务:

var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var loadTask = Task<List<OrderItemViewModel>>.Factory.StartNew(() =>
{
       throw new Exception("derp");
});

var errorContinue = loadTask.ContinueWith(t =>
    {
        MainViewModel.RemoveViewModel(this);
    }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiScheduler);

继续被击中,但几秒钟后我在应用程序中收到此错误:

等待任务也没有观察到任务的异常 或访问其 Exception 属性。结果,未观察到 异常被终结器线程重新抛出。

这与 uiScheduler 有关吗?类似问题的解决方法基本上就是我在做的A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was

【问题讨论】:

    标签: .net task-parallel-library task continuations unobserved-exception


    【解决方案1】:

    您需要实际处理(或至少观察)异常:

    var errorContinue = loadTask.ContinueWith(t =>
    {
        // Observe/acknowledge the exception.  
        // You can use t.Wait(), which throws, or just grab the exception
        var exception = t.Exception; 
        MainViewModel.RemoveViewModel(this);
    }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiScheduler);
    

    这是因为documentation on exception handling in the TPL的这一行:

    如果您不等待传播异常的任务或访问其 Exception 属性,则当任务被垃圾回收时,异常会根据 .NET 异常策略升级。

    在您的情况下,您有一个延续,但您从未真正“等待异常”或访问它的异常属性。我的回答(在您发布的相关问题中)有效的原因是我实际上使用通过延续传递的任务上的异常属性。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-25
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多