0
votes

I have a web API over net core 3.0 and my API is using a mail DLL where I do some operations.

Web API controller:

_mailService.SendEmail();

Mail DLL:

public void SendEmail()
{
     Console.Writeline("Registering at database");

     RegisterAtDatabase();  //Do some stuff at database

     SendMailToUser();   //Send mail to user. His operation takes about 1 minute

     Console.Writeline("End mail proccess");
}

private void SendMailToUser()
{
     Console.Writeline("Creating and sending mail");
     
    //Here some stuff to send the mail. It takes about 1 minute
     
    Console.Writeline("Mail sended");
}

I want to call _mailService.SendEmail() and not wait for the whole process. I want to write at the database and not wait for email sending process. So console output should be....

Registering at database
Creating and sending mail
End mail proccess
//After 1 minute
Mail sended

Is that possible using Task Async and await in some way?

I wanna return the control to the API while the email is sending.

Thanks

2

2 Answers

0
votes

You can use background Task queue for this kind of works and run them in the background.

full info at Microsoft Documents Background tasks with hosted services in ASP.NET Core

0
votes

Is that possible using Task Async and await in some way?

No, that's not what async is for.

The proper solution is to write the work (e.g., "send this message to this email address") to a reliable queue (e.g., Azure Queue / Amazon SQS / etc), and then have a separate background process read and process that queue (e.g., ASP.NET Core background service / Azure Function / Amazon Lambda / etc).