你不需要任务。 SendAsync是异步的并使用另一个线程自我。任务不会加速你邮寄。
UPDATE: 当我解决同样的问题,我使用任务和同步发送。似乎SendAsync并非如此异常。这是我的代码示例(这是不希望的HttpContext):
public void SendMailCollection(IEnumerable<Tuple<string, string, MailAddress>> 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<string, string, MailAddress> 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;
}
Hey Matt!感谢您的参考,这看起来不错,它是否异步发送100%,我听说有人说MVCMailer是伪异步哈哈。谢了哥们! – Baconbeastnz
没有问题!我在这张桌子上撞了一下桌子:) – Matt
@ Matt,它很棒!谢谢!!! =) –