英文异常信息:
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
|
请发表评论