Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么TaskScheduler.UnobservedTaskException不会触发?_C#_Debugging_Task Parallel Library_Task_Unhandled Exception - Fatal编程技术网

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=nullGC.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.");
}