When I use SmtpClient's SendAsync to send email, how do I dispose the smtpclient
instance correctly?
Let's say:
MailMessage mail = new System.Net.Mail.MailMessage()
{
Body = MailBody.ToString(),
IsBodyHtml = true,
From = new MailAddress(FromEmail, FromEmailTitle),
Subject = MailSubject
};
mail.To.Add(new MailAddress(i.Email, ""));
SmtpClient sc = new SmtpClient(SmtpServerAddress);
//Add SendAsyncCallback to SendCompleted
sc.SendCompleted += new SendCompletedEventHandler(SendAsyncCallback);
//using SmtpClient to make async send (Should I pass sc or mail into SendAsyncCallback?)
sc.SendAsync(mail, sc);
In the SendAsyncCallback
method, should I call sc.Dispose()
, or mail.Dispose()
?
I checked MSDN document, one example calls MailMessage.Dispose(), but will this dispose method also dispose the SmtpClient
instance?
You should dispose both the MailMessage
and the SmtpClient
in SendAsyncCallback
.
Disposing the MailMessage will not dispose the SmtpClient automatically (because you might want to send two messages with the same SmtpClient, and you wouldn't want the client to be disposed as soon as you disposed the first message).