c# - Entity Framework 核心 : ToList() vs ToListAsync()

标签 c# asp.net-core task-parallel-library

请考虑 ASP.NET Core Controller 中的异步 GetAccountProperties 方法:

public class CreditAccountController : Microsoft.AspNetCore.Mvc.Controller
{
    private readonly ICreditAccountManager _creditAccountManager;

    public CreditAccountController(
        ICreditAccountManager creditAccountManager
    {
        _creditAccountManager = creditAccountManager;
    }


    [HttpGet]
    public async Task<IActionResult> GetAccountProperties(...)
    {
        var result = await _creditAccountManager.GetPropertiesAsync(...);
        if (accountResult.Code == ResponseCode.Success)
            return Ok(result.Value);
        else 
            return NotFound();
    }
}

以及 CreditAccountManager 存储库中 GetPropertiesAsync() 方法的以下实现。

第一个实现使用 .ToList() 方法:

public Task<Result<List<GeneralAccount>>> GetAccountPropertiesAsync(...)
{
    var properties = _generalDatabaseContext.AccountProperties.Where(...).ToList();
    result.Code = ResponseCode.Success;
    result.Value = accounts;
    return Task.FromResult(result);
}

第二个使用 .ToListAsync() 方法和嵌套的 async/await:

public async Task<Result<List<GeneralAccount>>> GetAccountPropertiesAsync(...)
{
    var properties = await _generalDatabaseContext.AccountProperties.Where(...).ToListAsync();
    result.Code = ResponseCode.Success;
    result.Value = accounts;
    return result;
}

考虑到存储库方法中没有其他 EF 调用,并且 Controller 的方法已经是异步的,存储库方法的哪个实现在性能方面更好?

最佳答案

就性能而言,ToListAsync 可能性能更差,因为异步总是带来开销。

这并不是人们使用异步的真正原因。 由于您的数据库调用基本上是异步的,因此在同步选项中,您的服务器线程会等待数据库调用完成,然后再运行其余工作并返回结果。

在异步方法中,线程可以在等待数据库调用完成时处理其他请求。 因此它提供了更好的吞吐量。 我会一直使用异步方法,因为将 Controller 操作标记为异步然后同步执行最大的 IO 操作是毫无意义的。

也就是说,考虑性能的最佳选择是衡量。 进行一项同步操作和另一项异步操作。 然后测量单个请求响应时间和吞吐量。 然后,您可以根据实际数字做出决定。

关于c# - Entity Framework 核心 : ToList() vs ToListAsync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52588644/

相关文章:

c# - Appsetting.json 读取 Controller 类中键的值,空白?

c# - 如何更好地理解 "Async - Handling multiple Exceptions"文章中的代码/语句?

multithreading - TPL : Background thread completion notification?

visual-studio-2013 - aspnet50目标框架是什么,我可以从VS2013引用它吗?

c# - 如何将 Dictionary<string, Task<int>> 转换为 Task<Dictionary<string, int>>

c# - 在 DropDownList 中添加分隔符

c# - WPF 窗口大小不受 TabTip 键盘影响

javascript - 无法绑定(bind)到 'ngModule',因为它不是 'input' 的已知属性。在 Angular 2 asp.net 核心

c# - ConfigureAwait 将继续推送到池线程

c# - 将 Dictionary<string, string> 转换为 Dictionary<string, object> 的最简单方法是什么?