.SendMailAsync() use in MVC

后端 未结 3 889
有刺的猬
有刺的猬 2020-12-12 21:30

I am trying to send email from my MVC application, it sends fine when I use the .Send() method but takes a while to come back so I wanted to use the .SendMailAsync() functio

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 22:18

    I think the below does what you're trying to accomplish:

    Modify your controller as below:

    public async Task Index()
    {
        Email email = new Email();
        email.SendAsync();
    }
    

    And in your Email class add the SendAsync method as below

    public async Task SendAsync()
    {
        await Task.Run(() => this.send());
    }
    

    The action will return before the email is sent and the request will not be blocked.

    Try to see the behaviour with default mvc template with this code:

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        LongRunningTaskAsync();
        return View();
    }
    
    public static async Task LongRunningTaskAsync()
    {
        await Task.Run(() => LongRunningTask());
    }
    
    public static void LongRunningTask()
    {
        Debug.WriteLine("LongRunningTask started");
        Thread.Sleep(10000);
        Debug.WriteLine("LongRunningTask completed");
    }
    

    The login page will be displayed instantly. But output window will display "LongRunningTask completed" 10 seconds later.

提交回复
热议问题