C# 为什么TaskScheduler.UnobservedTaskException不会触发?
我有一个应用程序,目标是C# 为什么TaskScheduler.UnobservedTaskException不会触发?,c#,debugging,task-parallel-library,task,unhandled-exception,C#,Debugging,Task Parallel Library,Task,Unhandled Exception,我有一个应用程序,目标是.NET4,运行在.NET4.6.1机器上,具有以下app.config: <configuration> <runtime> <ThrowUnobservedTaskExceptions enabled="true"/> </runtime> </configuration> 但是无论构建类型是Debug还是Release,都不会触发该事件。发生了什么?要实现预期的行为,您可以在使用Relea
.NET4
,运行在.NET4.6.1
机器上,具有以下app.config
:
<configuration>
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>
</configuration>
但是无论构建类型是
Debug
还是Release
,都不会触发该事件。发生了什么?要实现预期的行为,您可以在使用Release时按照上面的注释删除GC.KeepAlive(任务)
或
您可以设置task=null调用GC.Collect()之前的code>代码>以确保任务已收集。
您可以找到另一个相关的答案,可能会添加更多细节。删除GC.KeepAlive(任务)
还必须使用Release,因为调试会延长本地变量的生存期以实现可调试性。
static void Main(string[] args)
{
SetupUnobservedTaskExceptionHandling();
var task = Task.Factory.StartNew(() =>
{
Console.WriteLine("Task started");
var innerException = new InvalidOperationException("No way!");
throw new ApplicationException("Ooops!", innerException);
});
Thread.Sleep(1000);
// The task should be in faulted state before collection for the exception event to bubble up
Console.WriteLine($"Task Status: {task.Status}");
GC.Collect();
GC.WaitForPendingFinalizers();
GC.KeepAlive(task);
Console.ReadLine();
}
[HandleProcessCorruptedStateExceptions]
public static void SetupUnobservedTaskExceptionHandling()
{
Console.WriteLine("Setting up unobserved task exception handling...");
TaskScheduler.UnobservedTaskException += (sender, args) =>
{
Console.WriteLine("Boooom!: {0}", args);
};
Console.WriteLine("Set up unobserved task exception handling.");
}