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
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.