我有一个控制器,其控制器方法如下:
[Route("GetDashboard")]
[HttpPost("GetDashboard")]
public async Task<IActionResult> PostDashboard([FromBody]Period period)
{
Debug.WriteLine("PostDasboard in");
var eventTimer = new EventTimer();
var forDate = period.FromDate;
var q = GetMySales(new ReportFilterModel { FromDate = forDate.AddDays(-31), UntilDate = forDate });
eventTimer.NextEvent("PostDashboard");
var r = await (from i in q
group i by i.Order.Shift.Site into s
select new
{
id = s.Key.Key,
name = s.Key.Name,
days = from i in s
group i by i.Order.Shift.AltTrade into d
select new
{
date = d.Key.GetEpochTicks(),
total = d.Sum(i => i.Sell),
qty = d.Sum(i => i.Quantity)
}
}).ToListAsync();
eventTimer.NextEvent($"Got List: {r.Count()}");
var result = Json(r);
if (_timing || (eventTimer.Elapsed >= 5000)) // More than sec..
await _eventLogger.DebugAsync("Timing", eventTimer.Final, null);
Debug.WriteLine("PostDasboard Out");
return result;
}
我添加了一些位来跟踪总体时间。该方法本身大约需要 3 秒。之后,响应完成之前可能还需要 12 到 30 秒:Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action OnlineUsers.Controllers.CloudTradeController.PostDashboard (OnlineUsers) in 35352.5891ms Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 35399.931ms 200 application/json; charset=utf-8};
延迟方法唯一不同的是嵌套的 Json。有人见过类似的延迟吗?还有其他工具可以更接近延迟的位置吗?
答案1
延迟只是对象序列化缓慢。延迟可以移至方法内部,如下所示。所以问题更多是:为什么序列化嵌套列表 (10 x 31) 中的 310 个对象需要 30 多秒?我是否在某些地方使用了错误的设置?
var result = Content(JsonConvert.SerializeObject(r));
答案2
问题在于“days”部分仍然只是 IEnumerable。因此,只有在序列化时,才会从数据库中获取。通过添加 ToList(),它们可以更快地实现。然而,这只是将(相同的)时间从序列化移回查询。看起来 linq 不太适合嵌套总计。或者有更好的模式吗?