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;
}
}
That way the client will be disposed even if an exception is thrown during the
Sendmethod call. You should very rarely need to callDisposeexplicitly – it should almost always be in ausingstatement.However, it’s not clear how the attachments are involved here. Does your class implement
IDisposableitself? 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: