C# 報錯:未通過等待任務或訪問任務的 Exception 屬性觀察到任務的異常。因此,終結器線程重新引發了未觀察到的異常。


英文異常信息:

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 rethrown by the finalizer thread.

如果創建了一個任務Task,並且從未調用過task.Wait()或嘗試檢索Task<T>的結果,
那么當垃圾收集器收集該任務時,它會在完成期間拆除應用程序。
有關詳細信息,請參閱 MSDN 上有關 TPL 中的異常處理的頁面Exception handling (Task Parallel Library)
中文版異常處理(任務並行庫)

可以通過ContinueWith處理異常。 可以編寫為一個簡單的擴展方法:

public static void LogExceptions(this Task task)
{
    task.ContinueWith( t =>
    {
         var aggException = t.Exception.Flatten();
         foreach(var exception in aggException.InnerExceptions)
             LogException(exception);
    }, 
    TaskContinuationOptions.OnlyOnFaulted);
}

使用它:

Task.Factory.StartNew( () => 
   { 
       // Do your work...
   }).LogExceptions();

另外一種方式是訂閱TaskScheduler.UnobservedTaskException

參考資料

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM