ASP.NET Core 6 Web API : best way to pause before resending email

20 views Asked by At

I have an ASP.NET Core 6 Web API. It is not using async. It was supposed to be a learning project, so I kept it simple, but now it's in production (woo). Because of this, I can't just rewrite the whole thing to use async.

In the Log4net stuff we have a SMTP appender that sends an email whenever an error is logged.

If sending the email with the error fails I want to retry

public void SendEmail(string messageBody)
{
    bool sent = false;

    // try 3 times to send the email, before failing - EWB
    try
    {
        sent = SendEmailInner(messageBody);
    }
    catch (Exception e)
    {
        try
        {
            sent = SendEmailInner(messageBody);
            return;
        }
        catch (Exception ex) 
        {
            try
            {
                sent = SendEmailInner(messageBody);
                return;
            }
            catch (Exception ex2)
            {
                throw new Exception( "Log4NetSmtpAppender::SendEmail(...) - Failed on try 3 to send email ", ex2);
            }

            if (!sent) 
                throw new Exception( "Log4NetSmtpAppender::SendEmail(...) - Failed on try 2 to send email ", ex );
        }

        if (!sent) 
            throw new Exception( "Log4NetSmtpAppender::SendEmail(...) - Failed all 3 attempts to send email ", e);
    }
}

I'd like to pause for 1 second before retrying, but I don't want to block the main thread of the Web API and cause problems with it missing requests.

So Thread.Sleep(1000) seems dangerous.

What is the best way to pause for 1 second in this context?

0

There are 0 answers