英文異常信息:
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