6

我有一項任務的延續來處理錯誤:任務延續(OnlyOnFaulted)仍然得到未觀察到的異常

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

回答

6

您需要實際處理(或至少觀察)除外:

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異常策略升級異常。

對於您的情況,您有一個延續,但您從未實際「等待異常」或訪問它的異常屬性。我的回答(在你發佈的相關問題中)的工作原理是我實際上使用通過延續傳遞的任務上的Exception屬性。

+0

由於寫了這個答案,微軟已經改變了.NET例外策略。請訪問https://msdn.microsoft.com/en-us/library/hh367887.aspx#core查看未查看的例外情況 –

相關問題