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

学习技术最好的文档就是官方文档,没有之一。
还有学习资料Microsoft LearnCSharp LearnMy Note
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的推荐按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下关注

原文地址:https://www.cnblogs.com/Lulus/p/15746189.html