Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Task<T> calls without async/await

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!

like image 942
user2961319 Avatar asked Aug 06 '26 08:08

user2961319


1 Answers

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");
      });
    }
like image 131
Davit Tvildiani Avatar answered Aug 09 '26 01:08

Davit Tvildiani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!