Karunaker Reddy V Karunaker Reddy V - 3 months ago 17
C# Question

How can I get 'fire and forget' behaviour from c# console code to web api

Check the below block of code. I need fire and forget behavior while calling sendMail method (i.e. while calling api). With this block of code I'm getting TaskCancelledException sometimes. Please help

private void ProcessMails()
{
while(true)
{
var mailsToBeProcessed = getAllMailsToBeProcessed(alreadySent, numOfMailsToBeProcessed);

freach(var mail in Mails)
{
sendMail("mailsendingApiUrl", mail)
alreadySent++;
}

Thread.Sleep(60000);
}
}

private async void sendMail(string apiEndPoint, MailContent mailContent)
{
using (var client = new HttpClient())
{
await client.PostAsJsonAsync(apiEndPoint, mailContent.ContentId);
}
}

Answer

Try this:

private void ProcessMails()
{
 while(true)
 {
  var mailsToBeProcessed = getAllMailsToBeProcessed(alreadySent, numOfMailsToBeProcessed);

   foreach(var mail in mailsToBeProcessed)
   {
     sendMail("mailsendingApiUrl", mail).Wait();
     alreadySent++;
   }
  }
}

private async Task sendMail(string apiEndPoint, MailContent mailContent)
{
    using (var client = new HttpClient())
    {
         await client.PostAsJsonAsync(apiEndPoint, mailContent.ContentId).ConfigureAwait(false);
    }
 }