C# how to correctly dispose of an SmtpClient?

后端 未结 6 1122
小鲜肉
小鲜肉 2020-12-05 12:57

VS 2010 code analysis reports the following:

Warning 4 CA2000 : Microsoft.Reliability : In method \'Mailer.SendMessage()\', object \'client\' is not disposed along

6条回答
  •  再見小時候
    2020-12-05 13:52

    I would do something like that:

    class Attachments : List, IDisposable
    {
      public void Dispose()
      {
        foreach (Attachment a in this)
        {
          a.Dispose();
        }
      }
    }
    
    class Mailer : IDisposable
    {
      SmtpClient client = new SmtpClient();
      Attachments attachments = new Attachments();
    
      public SendMessage()
      {
        [... do mail stuff ...]
      }
    
      public void Dispose()
      {
        this.client.Dispose();
        this.attachments.Dispose();
      }
    }
    
    
    [... somewhere else ...]
    using (Mailer mailer = new Mailer())
    {
      mailer.SendMail();
    }
    

    This would allow reusing the SmtpClient Object if you want to send multiple mails.

提交回复
热议问题