![](/img/trans.png)
[英]Notify progress in asynchronous long jobs in asp.net core with signalR and async await keyword
[英]Asynchronous programming with async and await using ASP.NET Core
我正在尝试使用async
和await
使用异步编程来计算一些值并使用 ASP.NET Core 2.x 定期保存在数据库中。 下面显示的方法不是从线程池中执行的。
public async void CalculateCIndex(int CIndexId)
{
List<string> UserIds = _context.ApplicationUsers
.Where(m => m.EmailConfirmed == true)
.Select(m => m.Id).ToList();
for (int i = 0; i < UserIds.Count; i += 10)
{
var temp = UserIds.Skip(i).Take(10);
foreach (var Id in temp)
{
await Task.Run(async () =>
{
await CIndexCal(Id, CIndexId);
});
}
await Task.Delay(6000);
}
}
public async Task CIndexCal(string Id, int CIndexId)
{
_context.CIndexMember.Add(new CIndexMember
{
NCIndex = (decimal)((AindexAfterRar + Power) / CI.TotalCindex)
});
_context.SaveChanges();
}
您可以在这里找到好的答案: async/await - 何时返回任务与无效?
您的方法 CIndexCal 被声明为异步但它根本不是异步的,因为您没有在内部使用异步方法。 为了改变这一点,你可以改变:
_context.SaveChanges();
到
await _context.SaveChangesAsync();
然后而不是:
await Task.Run(async () =>
{
await CIndexCal(Id, CIndexId);
});
您只需要:
await CIndexCal(Id, CIndexId);
我不确定你为什么要拖延,我认为你不需要这个:
await Task.Delay(6000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.