Properly disposing resources used by SmtpClient

孤街浪徒 提交于 2020-01-14 08:20:14

问题


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("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);
        }
    }

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1128390/properly-disposing-resources-used-by-smtpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!