I have a .NET Core console application. The exception that occurs within a nested async/await is never thrown:
static async Task Main(string[] args)
{
try
{
var f = new TaskFactory(TaskScheduler.Current);
await f.StartNew(async () =>
{
var x = 0;
if (x == 0)
throw new Exception("we have a problem");
await Task.Delay(1);
});
}
catch(Exception)
{
// never reaches here
}
}
If I remove the inner async, and drop the call to await Task.Delay(1), the exception is caught.
That's a classic trap. TaskFactory expects a Func<T> and returns a Task<T>. In your case, T is Task, therefore you end up with a Task<Task> and you need to await both the inner and the outer task. Use Unwrap for this:
await f.StartNew(async () =>
{
var x = 0;
if (x == 0)
throw new Exception("we have a problem");
await Task.Delay(1);
}).Unwrap();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With