Send async e-mails

前端 未结 4 1175
一整个雨季
一整个雨季 2020-12-09 19:53

I am using ASP.NET MVC 3 with MVCMailer, I tried to send e-mails using SendAsync, but actually it still take longer.

So I am trying to use Task.Factory like the code

4条回答
  •  情歌与酒
    2020-12-09 20:33

    You dont need tasks. SendAsync is asynchronous and use another thread self. Tasks dont accelerate you mailing.

    UPDATE: When i resolve same problem i use task and synchronous send. It seems that SendAsync was not so asynchrous. It is sample of my code (it is not want HttpContext):

    public void SendMailCollection(IEnumerable> mailParams)
        {
            var smtpClient = new SmtpClient
            {
                Credentials = new NetworkCredential(_configurationService.SmtpUser, _configurationService.SmtpPassword),
                Host = _configurationService.SmtpHost,
                Port = _configurationService.SmtpPort.Value
            };
    
            var task = new Task(() =>
                                    {
                                        foreach (MailMessage message in mailParams.Select(FormMessage))
                                        {
                                            smtpClient.Send(message);
                                        }
    
                                    });
            task.Start();
        }
    
        private MailMessage FormMessage(Tuple firstMail)
        {
            var message = new MailMessage
                {
                    From = new MailAddress(_configurationService.SmtpSenderEmail, _configurationService.SmtpSenderName),
                    Subject = firstMail.Item1,
                    Body = firstMail.Item2
                };
            message.To.Add(firstMail.Item3);
            return message;
        }
    

提交回复
热议问题