1

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:

  1. 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.
  2. How does one properly use using to dispose off classes like SmtpClient and MailMessage in async mode?
Mayank Pathak
  • 3,621
  • 5
  • 39
  • 67
DeepSpace101
  • 13,110
  • 9
  • 77
  • 127

1 Answers1

0

See here for an msdn example on the async smtpclient.
In this example they are not using dispose as (and this is a minor guess) the using will wait on the async operation to complete.
For testing purposes try removing the using statement, i expect the sendAsync to be faster then the send.
Offcourse you're not dispoing the smtpclient object properly, one way to handle the disposing is to create a new thread which handles the email the old skool way. You wouldn't have the cleanness of SendAssync but at least you're sure that the user gets instant feedback + the smtpclient is disposed properly.

Edit: an even better solution is to use the event sendcompleted and dispose the smtpclient there.
see here for an example

Community
  • 1
  • 1
Kristof
  • 3,267
  • 1
  • 20
  • 30