'TaskScheduler.UnobservedTaskException not firing because of a switch case
Using the .Net Framework 4.8 and VS 2022, in the following program, UnobservedTaskException is raised correctly
internal class Program
{
static void Main(string[] args)
{
// Listen to UnobservedTaskException
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
// Launch a task that will throw an exception
Task.Run(() =>
{
throw new ArgumentException("boom");
});
// Run the GC periodically so that UnobservedTaskException gets triggered
Task.Run(async () =>
{
while (true)
{
await System.Threading.Tasks.Task.Delay(500);
GC.Collect();
GC.WaitForPendingFinalizers();
}
});
Console.ReadLine();
}
private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Console.WriteLine(e.Exception.Message);
}
}
However in this slightly different one that should behave exactly the same (the Console.Readline() is now wrapped by a switch statement), the UnobservedTaskException is not triggered. What am I missing ?
internal class Program
{
static void Main(string[] args)
{
// Listen to UnobservedTaskException
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
// Launch a task that will throw an exception
Task.Run(() =>
{
throw new ArgumentException("boom");
});
// Run the GC periodically so that UnobservedTaskException gets triggered
Task.Run(async () =>
{
while (true)
{
await System.Threading.Tasks.Task.Delay(500);
GC.Collect();
GC.WaitForPendingFinalizers();
}
});
string dummy = "whatever";
switch (dummy)
{
default:
Console.ReadLine();
break;
}
}
private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Console.WriteLine(e.Exception.Message);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
