How do I avoid a delay when sending email from my application?

前端 未结 6 958
深忆病人
深忆病人 2021-01-26 03:23

I have a small console application. It checks a few settings, makes some decisions, and sends an email. The problem is the email doesn\'t actually get sent until my application

6条回答
  •  自闭症患者
    2021-01-26 04:10

    SmptClient supports async sending of mail via SendAsync, however in practice in a web application this hangs the request thread.

    To avoid blocking I recommend using the ThreadPool to fire off the email in a background thread. This won't block your application.

    ThreadPool.QueueUserWorkItem(o => {
        using (SmtpClient client = new SmtpClient(...))
        {
            using (MailMessage mailMessage = new MailMessage(...))
            {
                client.Send(mailMessage, Tuple.Create(client, mailMessage));
            }
        }
    }); 
    

提交回复
热议问题