等待任务或访问其异常属性都没有观察到任务的异常.结果,未观察到的异常是 [英] 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

查看:23
本文介绍了等待任务或访问其异常属性都没有观察到任务的异常.结果,未观察到的异常是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么意思以及如何解决?

我正在使用 TPL 任务.

整个错误

<块引用>

等待任务或访问其异常属性都没有观察到任务的异常.结果,未观察到的异常被终结器线程重新抛出.

在 System.Threading.Tasks.TaskExceptionHolder.Finalize()

mscorlib

解决方案

如果您创建了一个任务,并且您从未调用 task.Wait() 或尝试检索任务的结果Task,当垃圾收集器收集任务时,它会在终结过程中拆除您的应用程序.有关详细信息,请参阅关于 TPL 中的异常处理 的 MSDN 页面.>

这里最好的选择是处理"异常.这可以通过延续来完成——您可以将延续附加到任务,并记录/吞下/等发生的异常.这提供了一种干净的方式来记录任务异常,并且可以写成一个简单的扩展方法,即:

public static void LogExceptions(本任务任务){task.ContinueWith( t =>{var aggException = t.Exception.Flatten();foreach(aggException.InnerExceptions 中的 var 异常)日志异常(异常);},TaskContinuationOptions.OnlyOnFaulted);}

通过上述内容,您可以通过以下方式阻止任何任务拆除应用程序并对其进行记录:

Task.Factory.StartNew(() =>{//做你的工作...}).LogExceptions();

或者,您可以订阅 TaskScheduler.UnobservedTaskException 并在那里处理.

What does this mean and how to resolve it?

I am using TPL tasks.

The whole error

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.

at System.Threading.Tasks.TaskExceptionHolder.Finalize()

mscorlib

解决方案

If you create a Task, and you don't ever call task.Wait() or try to retrieve the result of a Task<T>, when the task is collected by the garbage collector, it will tear down your application during finalization. For details, see MSDN's page on Exception Handling in the TPL.

The best option here is to "handle" the exception. This can be done via a continuation - you can attach a continuation to the task, and log/swallow/etc the exception that occurs. This provides a clean way to log task exceptions, and can be written as a simple extension method, ie:

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);
}

With the above, you can prevent any task from tearing down the app, and logging it, via:

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

Alternatively, you can subscribe to the TaskScheduler.UnobservedTaskException and handle it there.

这篇关于等待任务或访问其异常属性都没有观察到任务的异常.结果,未观察到的异常是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆