-2

Jon Skeet says

The output shows Fetched the task before it fails. The exception has been thrown synchronously before that output is written, because there are no await expressions before the validation

Is there any guarantee about the fact the exception has been thrown synchronously before that output is written ?

Why cannot be the output text(Fetched the task) written out at first?

async Task Main()
{
    Task<int> task = ComputeLengthAsync(null);
    Console.WriteLine("Fetched the task");
    int length = await task;
    Console.WriteLine("Length: {0}", length);
}

static async Task<int> ComputeLengthAsync(string text)
{
    if (text == null)
    {
        throw new ArgumentNullException("text");
    }
    await Task.Delay(5000);
    return text.Length;
}
Hax
  • 133
  • 9

1 Answers1

2

Is there any guarantee about the fact the exception has been thrown synchronously before that output is written ?

Yes. async methods begin executing synchronously. In fact, if there is no await in the method at all, then the compiler will warn you that the entire method will run synchronously.

Why cannot be the output text(Fetched the task) written out at first?

The output is written out. The exception is not thrown directly; since it is thrown in an async method, the exception is captured and placed on the returned task. Then when the await task; line is run, the await retrieves the exception from the task and (re-)throws it.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810