Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to correctly dispose of an SmtpClient?

Tags:

c#

.net-4.0

VS 2010 code analysis reports the following:

Warning 4 CA2000 : Microsoft.Reliability : In method 'Mailer.SendMessage()', object 'client' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'client' before all references to it are out of scope.

My code is :

public void SendMessage()     {         SmtpClient client = new SmtpClient();          client.Send(Message);         client.Dispose();          DisposeAttachments();      } 

How should I correctly dispose of client?

Update: to answer Jons question, here is the dispose attachments functionality:

private void DisposeAttachments() {     foreach (Attachment attachment in Message.Attachments)     {         attachment.Dispose();     }     Message.Attachments.Dispose();     Message = null;  } 

Last Update full class listing (its short)

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Mail;  public class Mailer {     public MailMessage Message     {         get;         set;     }      public Mailer(MailMessage message)     {         this.Message = message;      }      public void SendMessage()     {         using (SmtpClient client = new SmtpClient())         {             client.Send(Message);         }         DisposeAttachments();      }      private void DisposeAttachments()     {         foreach (Attachment attachment in Message.Attachments)         {             attachment.Dispose();         }         Message.Attachments.Dispose();         Message = null;      } } 
like image 672
JL. Avatar asked May 06 '10 12:05

JL.


1 Answers

public void SendMessage() {     using (SmtpClient client = new SmtpClient())     {         client.Send(Message);     }     DisposeAttachments();  } 

That way the client will be disposed even if an exception is thrown during the Send method call. You should very rarely need to call Dispose explicitly - it should almost always be in a using statement.

However, it's not clear how the attachments are involved here. Does your class implement IDisposable itself? If so, that's probably the place to dispose of the attachments which are presumably member variables. If you need to make absolutely sure they get disposed right here, you probably need:

public void SendMessage() {     try     {         using (SmtpClient client = new SmtpClient())         {             client.Send(Message);         }     }     finally     {         DisposeAttachments();      } } 
like image 199
Jon Skeet Avatar answered Oct 14 '22 18:10

Jon Skeet