问题描述
这是什么意思以及如何解决?
我正在使用 TPL 任务.
整个错误
<块引用>在等待任务或访问其异常属性时未观察到任务的异常.结果,未观察到的异常被终结器线程重新抛出.
在 System.Threading.Tasks.TaskExceptionHolder.Finalize()
mscorlib
如果你创建了一个任务,并且你没有调用 task.Wait()
或者尝试检索一个任务的结果Task<T>
,当垃圾收集器收集到任务时,它会在终结期间关闭你的应用程序.有关详细信息,请参阅 TPL 中的异常处理 上的 MSDN 页面..p>
这里最好的选择是处理"异常.这可以通过延续来完成 - 您可以将延续附加到任务,并记录/吞下/等发生的异常.这提供了一种干净的方式来记录任务异常,并且可以写成一个简单的扩展方法,即:
public static void LogExceptions(this Task task){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.
这篇关于通过等待任务或访问其异常属性未观察到任务的异常.结果,未观察到的异常是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!