This code is merely for learning/test purpose:
I am deliberately throwing an Exception inside a Task.Run(...) and calling it from a WindowsForm ButtonClickEventHandler:
async void button_Click(object sender, EventArgs e)
{
try
{
await Task.Run(
() =>
{
throw new Exception("Foo");
}
);
}
catch (Exception ex) { }
}
When I debug the application and put a breakpoint to the catch statement, I see that the variable "ex" has the value null. Why is that and how can I capture the exception content? (If I use Task.Wait() or ContinueWith() afterwards it is captured correctly, but I want to know how to catch it when using await)
Here is the strange part: If I insert a "Debug.WriteLine(ex.Message);" statement inside the catch, ex is not null anymore. And if I remove the "Debug.WriteLine(ex.Message);" statement again and run the code ex is not null. Apparently on some runs ex has the value, sometimes it's just null.
Is that a Thread issue or is it just a Visual Studio bug?
Environment: Windows 10, VS 2019, .NET 5.0, Windows Forms Application