你不需要任务。SendAsync 是异步的并使用另一个线程自身。任务不会加速你的邮件。
更新:当我解决同样的问题时,我使用任务和同步发送。看来 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;
}