首页 > 解决方案 > 异步函数调用异步函数的 C# 性能影响

问题描述

我正在编写代码,最终从另一个异步方法调用异步方法。我想知道这种做法对性能的影响。它是否会导致每个 async-await 使用这么多线程?

一个例子会有所帮助

public async Task<IHttpActionResult> ControllerMethod() 
{
    :
    return await A1();
}

public async Task<R1> A1() 
{
    :
    var result = await A2();
    if (result != null) 
    {  
        A3() 
    }
    return result;
}

public async Task<R1> A2() 
{
    :
    var result = await A4();
    return result;
}

public void A3() 
{
    :
    // call to another async method without await
}

请帮助我理解-这是不好的做法吗?这是重构代码的结果

标签: c#.netasp.net-mvc

解决方案


成本和性能影响在于每个被标记为异步的方法都被转移到幕后的状态机中。所以必须处理更多的代码和状态机实例。

您可以避免使用重写的状态机,如下所示;如果该语句后面没有代码,您不必等待,只需按照下面的 A2 方法中的完成返回任务即可。

public Task<IHttpActionResult> ControllerMethod() 
{
    return A1();
}

public async Task<R1> A1() 
{
    var result = await A2();
    if (result !=  null)
    {  
        A3() 
    }
    return result;
}

public Task<R1> A2() 
{
    return A4();
}

public void A3() 
{
    // call to another async method without await
}

推荐阅读