所以我在创建用户的地方有这个功能控制器 批量创建用户后, 我想发送短信/电子邮件确认。 但是电子邮件的短信处理过程很慢。 (由于我使用第三方发送短信,因此我无法批量发送短信) 因此,我想要它,以便一旦它创建了用户,它就返回UI(模型),但其他线程仍在工作 发送短信/电子邮件功能。 请帮忙。非常感谢
例如:
public async Task<AjaxReturn> ImportUsers(Users[] users)
{
//there are lot of checks here which i have removed for showing
//save all the users at a time
var saved = await _accserver.SaveBulkUser(applicationUsers, userInfo.AccountId);
//this below method i want to call but dont want to wait till its finish,
// I want it to continue sending sms/emails
SendUserConfirmation(goesAllsavedUsersHere);
return AjaxReturnHelper.GetAjaxReturn(!isAllSaved) ? ResultTypes.Error : ResultTypes.Success);
}
private async void SendUserConfirmation(UsersListhere)
{
foreach(var user in userlist)
{
await _messageservice.sendsms(.....);
await _messageservice.sendemail(.....);
}
}
答案 0 :(得分:1)
我有一些建议:
请勿使用async void
,而应使用async Task
。
将foreach(var user in userlist)
更改为Parallel.ForEach(...)
,因为这些调用可以是异步的
使用回调函数,并通过SignalR将通知发送到WebUI,然后显示一条消息
public async Task<AjaxReturn> ImportUsers(Users[] users)
{
//there are lot of checks here which i have removed for showing
//save all the users at a time
var saved = await _accserver.SaveBulkUser(applicationUsers, userInfo.AccountId);
//this below method i want to call but dont want to wait till its finish,
// I want it to continue sending sms/emails
SendUserConfirmation(goesAllsavedUsersHere, () =>
{
// do something here
// you can try to call a SignalR request to UI and UI shows a message
});
return AjaxReturnHelper.GetAjaxReturn(!isAllSaved) ? ResultTypes.Error : ResultTypes.Success);
}
private async Task SendUserConfirmation(UsersListhere, Action doSomethingsAfterSendUserConfirmation)
{
Parallel.ForEach(userlist, async (user) =>
{
await _messageservice.sendsms(.....);
await _messageservice.sendemail(.....);
});
doSomethingsAfterSendUserConfirmation();
}