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 async
methods begin executing synchronously. The async
keyword transforms your method into a state machine, including code that catches thrown exceptions and places them on the returned task. Without the async
keyword, the method is just like any other method, and the exception is thrown directly.
To fix, add the async
keyword:
async Task Fail()
{
throw new Exception("ex");
}