1

I have an app targeting .NET4 running on a .NET4.6.1 machine with the following app.config:

<configuration>
  <runtime>
    <ThrowUnobservedTaskExceptions enabled="true"/>
  </runtime>
</configuration>

I then try to run the following expecting to see the message 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.");
}

But the event is never triggered regardless of a build type of Debug or Release. What is going on?

MaYaN
  • 6,683
  • 12
  • 57
  • 109

1 Answers1

2

To achievethe expected behavior you can follow the comments above and remove GC.KeepAlive(task) while using Release

or

you can set task = null; before calling GC.Collect(); to ensure that task is collected. Here you can find another related answer that maybe add some more detail.

Community
  • 1
  • 1
3615
  • 3,787
  • 3
  • 20
  • 35