【发布时间】:2015-07-28 09:56:59
【问题描述】:
我有一个 WebApi 控制器,其中一个部分是向一组用户发送电子邮件。
[HttpPost]
[Authorize]
[Route("{id}/Do")]
public async Task<HttpResponseMessage> Post(int id, Model model)
...
await _emailService.SendAsync(message);
...
现在是发送电子邮件的方法(SendGrid)
public override async Task SendAsync(MailMessage message)
{
var client =
new SmtpClient(SendGridServerName, SendGridServerPort)
{
Port = SendGridServerPort,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false
};
var credentials = new NetworkCredential(SendGridUserName, SendGridPassword);
client.EnableSsl = true;
client.Credentials = credentials;
message.From = new MailAddress(FromAddress);
await client.SendMailAsync(message);
}
一切正常,但速度很慢。我期待它很快,但await _emailService.SendAsync(message); 似乎不是异步的。它在那里停了一会儿。
有什么想法吗?
谢谢
【问题讨论】:
-
看看WebApi Async。 “单个请求可能会稍微慢一些”,但是当系统处于负载状态时,它会表现得更好。斯蒂芬克利假设电子邮件客户端是 SmtpServer,您最好使用new thread,这样您的操作就不会等待此完成。
-
我建议改用SendGrid SDK,他们有
Async使用REST API 的方法。 -
我刚刚更新了原始答案,指出了一些额外的细节,说明你可以做些什么来给你的用户提供一个快速的答案。
标签: c# email asynchronous asp.net-web-api sendgrid