簡體   English   中英

嵌套任務 <T> 沒有異步/等待的呼叫

[英]Nested Task<T> calls without async/await

這與以下帖子有關: 為什么一直使用Async / await

我很好奇在以下場景中會發生什么:

由於評論而更新:

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

Task Func1()
{
    return Func2();
}

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

整個過程是否會成為阻止呼叫? 或者因為實際上正在等待Func1(),UI可以繼續工作嗎? 最終是否需要在Func1()上添加async / await? 我玩過它但我實際上沒有發現任何差異,因此問題。 任何見解都會很棒,謝謝!

Asyncawait只是編譯器功能。

沒有await調用異步方法會導致它執行同步(阻塞)方式..

當你寫await所有代碼波紋管await被包裹在Task.ContinueWith()由編譯器全自動方法,這意味着,當任務完成下面的代碼在以后執行

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

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

將翻譯如下:

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

    public void method1(){
      method2().ContinueWith(x => {
        Console.WriteLine("Done");
      });
    }

沒有制作Func1async方法而不await Func2的唯一問題是任何拋出的異常都不會顯示Func1

最重要的是await適用於awaitablesTask / Task<T>等待的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM