通过等待任务或访问其异常属性,没有观察到任务的异常。因此,不可观察的例外是 [英] 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
问题描述
这是什么意思和解决方法?
What does this mean and how to resolve it?
我正在使用TPL任务。
I am using TPL tasks.
整个错误
通过等待任务或访问其异常属性,没有观察到任务的异常。因此,未定义的异常被终结者线程重新抛出。
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.
在System.Threading.Tasks.TaskExceptionHolder.Finalize()
at System.Threading.Tasks.TaskExceptionHolder.Finalize()
mscorlib
推荐答案
如果你创建一个任务, t任务调用 task.Wait()
,或尝试检索 Task
的结果,当任务由垃圾收集器收集,它将在最终确定期间拆除您的应用程序。有关详细信息,请参阅MSDN的有关 TPL中异常处理的页面。
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.
这里最好的选择是处理异常。这可以通过继续进行 - 您可以附加任务的延续,并记录/吞下/ etc发生的异常。这提供了一个干净的方式来记录任务异常,并可以作为一个简单的扩展方法,即:
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();
或者,您可以订阅 TaskScheduler.UnobservedTaskException 并处理它。
Alternatively, you can subscribe to the TaskScheduler.UnobservedTaskException and handle it there.
这篇关于通过等待任务或访问其异常属性,没有观察到任务的异常。因此,不可观察的例外是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!