当调用特定的 MVC 控制器方法时,我们会发送一封电子邮件。代码如下。在浏览器中对 AJAX 响应时间进行基准测试时,我们看到client.SendAsync(mail, null)
和client.Send(mail)
实现都花费了大约相同的时间,即 1.8 秒,而根本不发送邮件。
public ActionResult jsonPosted(int? id, SomeDataClass data)
{
...
// NOTE: remode 'using' statement for Async calls
// else no email ever sees light
using (SmtpClient client = new SmtpClient())
{
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("name@server.com", "password");
client.Port = 587;
client.Host = "smtp.server.com";
client.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("admin@server.com");
mail.To.Add("sales@server.com");
mail.Subject = "Coming soon: user " + newUser.Email + " registered on list";
mail.Body = "Email address is : " + newUser.Email + "\n";
mail.Body += "Date of signup is : " + newUser.SignupTime.ToString();
try
{
// Both take about 1.9 seconds ?!?!
//client.SendAsync(mail, null);
client.Send(mail);
}
catch (SmtpException e)
{
// bad smtp, no mail for you
}
}
...
return Json(dataIndependentOfEmail);
}
问题:
- 为什么这两种方法需要相同的时间?Async 应该立即返回,而 Sync 应该阻塞整个处理时间,对吗?据我了解,异步在工作期间消耗另一个线程并且该线程阻塞。但是,至少第一个线程上的用户应该会看到性能提升。
- 如何正确使用以异步模式
using
处理类?SmtpClient
MailMessage