I want to suppress exception triggered in the task. As I recall, some time ago I used this code to make it possible:
void Main(..)
{
Task Fail()
{
throw new Exception("ex");
}
Fail().ContinueWith(t =>
{
var ignored = t.Exception;
ignored?.Handle(e => true);
},
TaskContinuationOptions.OnlyOnFaulted |
TaskContinuationOptions.ExecuteSynchronously);
}
I see that when I run this in Console application (.NET 6) now, the only logic happens is making thrown exception (t.Exception) "observed" and then, this actually triggered exception is being pushed to the main method (outside task) and crashes my application.
Adding await like:
await (Fail().ContinueWith(..))
doesn't make difference.
I'm not sure why I remember it worked before, but any ideas how to make this logic?
As I explain on my blog, all
asyncmethods begin executing synchronously. Theasynckeyword transforms your method into a state machine, including code that catches thrown exceptions and places them on the returned task. Without theasynckeyword, the method is just like any other method, and the exception is thrown directly.To fix, add the
asynckeyword: