Difference between returning and awaiting a Task in an async method [duplicate]

There are 2 practical differences:

  1. The second option will not create the state machine mecanism that allows for async-await usage. That will have a minor positive effect on performance.
  2. The exception handling would be a little different. When you mark a method as async any exceptions are stored in the returned task (both from the asynchronous part and the synchronous one) and thrown only when the task is awaited (or waited). When it’s not async, the exceptions from the synchronous parts act just like in any other method.

My suggestion: Use the second one for the added performance boost but keep an eye out for exceptions and bugs.


An example that shows the difference:

public static async Task Test()
{
    Task pending = Task.FromResult(true);
    try
    {
        pending = SendAsync1();
    }
    catch (Exception)
    {
        Console.WriteLine("1-sync");
    }

    try
    {
        await pending;
    }
    catch (Exception)
    {
        Console.WriteLine("1-async");
    }

    pending = Task.FromResult(true);
    try
    {
        pending = SendAsync2();
    }
    catch (Exception)
    {
        Console.WriteLine("2-sync");
    }

    try
    {
        await pending;
    }
    catch (Exception)
    {
        Console.WriteLine("2-async");
    }
}

public static async Task SendAsync1()
{
    throw new Exception("Sync Exception");
    await Task.Delay(10);
}

public static Task SendAsync2()
{
    throw new Exception("Sync Exception");
    return Task.Delay(10);
}

Output:

1-async
2-sync

Leave a Comment