In a WPF app, I added two buttons, one which starts a Task and the other which forces GC to run:
private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Run(() =>
{
throw new Exception("Some Exception");
});
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
The task just throws an exception.
When running the app in Release config, I'm pressing first button and then the 2nd button and I'm expecting the app to crash. This doesn't happen, no matter how many times I press the buttons.
I am aware of the behavior of unobserved task swallowing exceptions in .NET 4.5: https://blogs.msdn.microsoft.com/pfxteam/2011/09/28/task-exception-handling-in-net-4-5/
I am confused however why once GC runs, the app doesn't crash. Per my understanding, Once the task is collected the eception should be thrown.
Also note I am aware of this question which doesn't answer my question Why doesn't my process terminate when Task has unhandled exception?
The comment marked as answer suggests to use ContinueWith
but this doesn't work either, the app doesn't crash, the exception is swallowed:
private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Run(() =>
{
throw new Exception("Some Exception");
}).ContinueWith(t =>
{
if (t.IsFaulted) { throw t.Exception.InnerException; }
});
}
I am already aware that awaiting on the Task makes the app to crash.