We're sending an email out when a particular MVC controller method is called. The code is as below. When benchmarking the AJAX response time inside a browser we see that the client.SendAsync(mail, null)
and client.Send(mail)
implementations BOTH take about the same time i.e. 1.8 seconds as compared to not sending the mail at all.
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);
}
Question:
- Why do the two methods take the same time? Async should return immediately while Sync should block for the entire processing time, right? As I understand Async consumes another thread and THAT thread blocks during work. However at least the user on the 1st thread should see a performance boost.
- How does one properly use
using
to dispose off classes likeSmtpClient
andMailMessage
in async mode?