为什么TaskScheduler.UnobservedTaskException不触发?
Why is the TaskScheduler.UnobservedTaskException does not trigger?
我在 .NET4.6.1
机器上有一个针对 .NET4
运行ning 的应用程序,具有以下 app.config
:
<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)
或
您可以在调用GC.Collect();
之前设置task = null;
以确保任务被收集。
Here 您可以找到另一个相关答案,可能会添加更多详细信息。
我在 .NET4.6.1
机器上有一个针对 .NET4
运行ning 的应用程序,具有以下 app.config
:
<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)
或
您可以在调用GC.Collect();
之前设置task = null;
以确保任务被收集。
Here 您可以找到另一个相关答案,可能会添加更多详细信息。