在顶层一直向下同步VS异步

时间:2017-09-01 16:38:46

标签: c# .net asynchronous async-await c#-5.0

以下哪一种是使用异步等待的最佳方式。

选项1 :异步等待所有函数

public async Task A()
{
   await B();
   //some code
}

public async Task<bool> B()
{
   var result= await C(); 
   //some code
   return result; 
}

public Task<bool> C()
{ 
   // not implemnted
}

OR

选项2 :异步等待只有顶级功能

 public async Task A()
    {
       await B();
       //some code
    }

    public async Task<bool> B()
    {
        var result= C().Result; 
        //some code
        return result; 

    }

    public Task<bool> C()
    { 
       // not implemnted
    }

1 个答案:

答案 0 :(得分:5)

选项1是正确的方法,2不应该这样做。如果您在callstack中的任何位置使用async,则不应在代码中的任务上调用.Result.Wait()。如果你这样做,很可能你最终会使你的程序陷入僵局。

更新:在旁注中,如果函数B中的代码不依赖于启动函数的同一个线程(没有UI工作),那么“最好”的方法就是

public async Task A()
{
   await B();
   //some code that interacts with the UI
}

public async Task<bool> B()
{
   var result= await C().ConfigureAwait(false); 
   //some code does does not interact with the UI
   return result; 
}

public Task<bool> C()
{ 
   // not implemnted
}

这使得系统可以使用任何可用的线程池线程,而不是等待继续运行时同步上下文可用。