3

This is kind of related to the following post: Why use Async/await all the way down

I am curious what happens in the following scenario:

Updated due to comment:

async Task FooAsync()
{
    await Func1();
    // do other stuff
}

Task Func1()
{
    return Func2();
}

async Task Func2()
{
    await tcpClient.SendAsync();
    // do other stuff
}

Does this whole process becomes a blocking call? Or because Func1() is actually awaited on, the UI can go and work on something else? Ultimately is it necessary to add the async/await on Func1()? I've played around with it but I don't actually notice any difference, hence the question. Any insight would be great, thanks!

Community
  • 1
  • 1

2 Answers2

3

Async and await are just compiler features.

Without await calling async method will cause it to execute synchronous (blocking) way..

When you are writing await all code bellow await is wrapped in Task.ContinueWith() Method by compiler automaticly, this means that when task is finished code below is executed later

public async Task<int> method2(){
  return Task.FromResult(1);
}

public void method1(){
  await method2()
  Console.WriteLine("Done");
}

will translate something like :

  public Task<int> method2(){
      return Task.FromResult(1);
    }

    public void method1(){
      method2().ContinueWith(x => {
        Console.WriteLine("Done");
      });
    }
Davit Tvildiani
  • 1,915
  • 3
  • 19
  • 29
  • Note: It is not as simple as just a `ContinueWith`, [here is a old answer of mine](http://stackoverflow.com/questions/20573625/how-does-async-await-not-block/20573825#20573825) where I explained the same concept in more detail if you want to see – Scott Chamberlain Mar 08 '16 at 20:03
  • And, if you don't use `async-await` it woun't block. – Paulo Morgado Mar 08 '16 at 22:27
0

The only problem of not making Func1 and async method and not awaiting Func2 in it is that any thrown exception won't show Func1.

The bottom line is that await works on awaitables and Task/Task<T> are awaitables.

Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59