Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception not thrown from nested async/await

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.

like image 440
Dan Avatar asked Dec 21 '25 04:12

Dan


1 Answers

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();
like image 92
Kevin Gosse Avatar answered Dec 23 '25 19:12

Kevin Gosse