views:

635

answers:

2

I have a C# service that runs continuously with user credentials (i.e not as localsystem - I can't change this though I want to). For the most part the service seems to run ok, but ever so often it bombs out and restarts for no apparent reason (servicer manager is set to restart service on crash).

I am doing substantial event logging, and I have a layered approach to Exception handling that I believe makes at least some sort of sense:

  • Essentially I got the top level generic exception, null exception and startup exception handlers.
  • Then I got various handlers at the "command level" (i.e specific actions that the service runs)
  • Finally I handle a few exceptions handled at the class level

I have been looking at whether any resources aren't properly released, and I am starting to suspect my mailing code (send email). I noticed that I was not calling Dispose for the MailMessage object, and I have now rewritten the SendMail code as illustrated below.

The basic question is:

  • will this code properly release all resources used to send mails?
  • I don't see a way to dispose of the SmtpClient object?
  • (for the record: I am not using object initializer to make the sample easier to read)

    private static void SendMail(string subject, string html)
    {
        try
        {
            using ( var m = new MailMessage() )
            {
                m.From = new MailAddress("[email protected]");
                m.To.Add("[email protected]");
                m.Priority = MailPriority.Normal;
                m.IsBodyHtml = true;
                m.Subject = subject;
                m.Body = html;
                var smtp = new SmtpClient("mailhost");
                smtp.Send(m);
            }
        }
        catch (Exception ex)
        {
            throw new MyMailException("Mail error.", ex);
        }
    }
    
+1  A: 

There are documented issues with the SmtpClient class. I recommend buying a third party control since they aren't too expensive. Chilkat makes a decent one.

Spencer Ruport
Thanks for the info - I might have to look at that. It's strange that the MailMessage object implements IDisposable, but the SmtpClient does not.
Glytzhkof
Yeah. There seems to be a work around posted on that link. May want to check that out.
Spencer Ruport
+1  A: 

I know this question is pre .Net 4 but version 4 now supports a Dispose method that properly sends a quit to the smpt server. See the msdn reference and a newer stackoverflow question.

Jeff