gpt4 book ai didi

c# - 异步 Web API 端点

转载 作者:行者123 更新时间:2023-11-30 16:49:31 25 4
gpt4 key购买 nike

以下 Web API 端点仍然出现以下错误:

"A second operation started on this context before a previous asynchronous operation completed."

由于我将 .ToListAsync 与从 Entity Framework 返回的数据一起使用,我假设问题出在 var user 行阻塞。

如何使该部分也异步?

[Route("Retailers/{search}")]
[HttpGet]
public Task<List<Lookup>> Retailers(string search)
{
var user = UserManager.FindById(User.Identity.GetUserId());
Guid userId = Guid.Parse(user.Id);

var companies = _unitOfWork.GetRepository<Company>().GetAll().Where(c => c.CompanyType == CompanyType.Retail &&
(c.UserID == null || c.UserID == userId) && c.CompanyName.StartsWith(search)).Take(5)
.Select(x => new Lookup { Id = x.Id, Name = x.CompanyName }).ToListAsync();

return companies;
}

最佳答案

您缺少 asyncawait 关键字。

  1. async 添加到方法签名中。
  2. await 添加到对 _unitOfWork.GetRepository...ToListAsync() 的调用中

代码:

[Route("Retailers/{search}")]
[HttpGet]
public async Task<List<Lookup>> Retailers(string search)
{
var user = UserManager.FindById(User.Identity.GetUserId());
Guid userId = Guid.Parse(user.Id);

var companies = await _unitOfWork.GetRepository<Company>().GetAll().Where(c => c.CompanyType == CompanyType.Retail &&
(c.UserID == null || c.UserID == userId) && c.CompanyName.StartsWith(search)).Take(5)
.Select(x => new Lookup { Id = x.Id, Name = x.CompanyName }).ToListAsync();

return companies;
}

这里有一个很好的异步编程链接作为引用:Asynchronous Programming with Async and Await .

关于c# - 异步 Web API 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36595914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com