[英]system.threading.task - why does TaskScheduler.UnobservedTaskException event not occur? Can I fix this?
[英]Why is the TaskScheduler.UnobservedTaskException does not trigger?
我有一个针对.NET4
的应用程序,该应用程序在带有以下app.config
的.NET4.6.1
计算机上运行:
<configuration>
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>
</configuration>
然后,我尝试运行以下命令,希望看到消息Boom!: ....
:
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.");
}
但是,无论构建类型为Debug
还是Release
都不会触发该事件。 到底是怎么回事?
要实现预期的行为,您可以按照上述说明操作,并在使用Release时删除GC.KeepAlive(task)
要么
您可以设置task = null;
在调用GC.Collect();
之前GC.Collect();
确保收集任务。 在这里,您可以找到另一个相关的答案,可能还会添加更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.