如何从 c# 控制台代码到 Web API 获取“即发即弃”行为

本文关键字:即发即弃 行为 获取 API 控制台 代码 Web | 更新日期: 2023-09-27 18:36:58

检查下面的代码块。我需要在调用 sendMail 方法时(即在调用 api 时)触发并忘记行为。使用这个代码块,我有时会收到任务取消异常。请帮忙

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);
    }
}

如何从 c# 控制台代码到 Web API 获取“即发即弃”行为

试试这个:

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);
    }
 }