Note that there are some explanatory texts on larger screens.

plurals
  1. POProperly disposing resources used by SmtpClient
    primarykey
    data
    text
    <p>I have a <strong>C# service</strong> that <strong>runs continuously</strong> 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 <strong>restarts for no apparent reason</strong> (servicer manager is set to restart service on crash).</p> <p>I am doing substantial <strong>event logging</strong>, and I have a <strong>layered approach</strong> to <strong>Exception handling</strong> that I believe makes at least some sort of sense:</p> <ul> <li>Essentially I got the <strong>top level</strong> generic exception, null exception and startup exception handlers. </li> <li>Then I got various handlers at the "<strong>command level</strong>" (i.e specific actions that the service runs)</li> <li>Finally I handle a few exceptions handled at the <strong>class level</strong></li> </ul> <p>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 <strong>MailMessage object</strong>, and I have now rewritten the SendMail code as illustrated below. </p> <p>The <strong>basic question</strong> is:</p> <ul> <li><strong>will this code properly release all resources used to send mails?</strong></li> <li>I don't see a way to <strong>dispose</strong> of the <strong>SmtpClient object</strong>?</li> <li>(for the record: I am not using object initializer to make the sample easier to read) </li> </ul> <pre class="lang-cs prettyprint-override"><code> private static void SendMail(string subject, string html) { try { using ( var m = new MailMessage() ) { m.From = new MailAddress("service@company.com"); m.To.Add("user@company.com"); 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); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload