通过等待任务或访问其异常属性未观察到任务的异常.结果,未观察到的异常是
- 作者: 我的大剑已经饥渴难耐
- 来源: 51数据库
- 2023-02-08
问题描述
这是什么意思以及如何解决?
我正在使用 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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
