以下代码(在单个 DbContext 上)导致“在上一个操作完成之前在此上下文上启动了第二个操作”。
[HttpGet]
[Route("api/[controller]/circuit")]
public async Task<IEnumerable<object>> GetallCircuits()
{
var circuits = await Task.WhenAll((await _context.Circuits.ToListAsync()).Select(async x => new
{
x.Id,x.FastestLap,x.LengthInmiles,Country = await _context.Countries.FirstOrDefaultAsync(c => c.Id == x.CountryId),Map = await _context.Maps.FirstOrDefaultAsync(m => m.Id == x.MapId),Locations = await _context.Locations.Where(l => l.CircuitId == x.Id).ToListAsync()
}));
return circuits;
}
我能够通过去掉 async/await
和 Task.WhenAll
部分并用 .Result
替换它们来解决这个问题,这在 .NET 中似乎是一个很大的禁忌。下面的固定示例:
[HttpGet]
[Route("api/[controller]/circuit")]
public async Task<IEnumerable<object>> GetallCircuits()
{
var circuits = (await _context.Circuits.ToListAsync()).Select(x => new
{
x.Id,Country = _context.Countries.FirstOrDefaultAsync(c => c.Id == x.CountryId).Result,Map = _context.Maps.FirstOrDefaultAsync(m => m.Id == x.MapId).Result,Locations = _context.Locations.Where(l => l.CircuitId == x.Id).ToListAsync().Result
});
return circuits;
}
我的三个问题是:
- 为什么会发生这种情况?
- “固定”代码是否干净?如果没有,请您提出更好的方法吗?
- 我可以只使用
.ToList()
而不是异步变体吗?
谢谢!