1
votes

For example, in the code below, the last method M2Async is synchronous and does not have async/await as otherwise there would need to be a call to M3Async after await and the call graph would continue?

For clarity (from C# in a Nutshell):

  • A synchronous operation does its work before returning to the caller.
  • An asynchronous operation does (most or all of) its work after returning to the caller.

    public void Main() { Task task = M1Async(); // some work int i = task.result; // use i etc }

    private async Task M1Async() { int i = await M2Async(); // some work return i; }

    private Task M2Async() { return Task.FromResult(2); }

1

1 Answers

4
votes

That depends a bit on what you mean by "synchronous". In some ways, all methods are synchronous (even async ones) - they just synchronously return something that can be awaited and which might have more things to do once awaited.

No, it doesn't have to be synchronous; your code could just as well be:

private async Task<int> M2Async()
{
    return await Task.FromResult(2);
}

or even just (although the compiler will detect that this is a smell, and is secretly synchronous):

private async Task<int> M2Async()
{
    return 2;
}

Neither of which would be particularly useful, but; they would work. In reality, most async methods will bottom out at something that is doing async IO - file-system, network, etc. In your example, there is nothing that will actually truly be async anyway - it will all be completed when the await is reached.