如何在后台运行的Controller中调用函数

问题描述 投票:-1回答:1

所以我有这个功能控制器,我在批量创建用户后创建用户,我想发送短信/电子邮件确认。但电子邮件短信过程使它变慢。 (因为我正在使用第三方发送短信,我无法进行批量短信)因此我想要它,以便一旦它创建了用户它返回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(.....);
  }
}
c# .net asp.net-core async-await asp.net-core-mvc
1个回答
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();
}
© www.soinside.com 2019 - 2024. All rights reserved.