문제

What is the proper way to dispose of SmtpClient and MailMessage while using SendAsync?

I have copied my code below.

{
...
var client = new SmtpClient {Host = _smtpServer};
client.SendCompleted += SendCompletedCallback;
var userState = mailMessage;
client.SendAsync(mailMessage, userState);
...
}

private static void SendCompletedCallback(object sender, 
    AsyncCompletedEventArgs e)
{
    // Get the unique identifier for this asynchronous operation.
    var mailMessage= (MailMessage)e.UserState;

    if (e.Cancelled)
    {
        Log.Info(String.Format("[{0}] Send canceled.", mailMessage));
    }
    if (e.Error != null)
    {
        Log.Error(String.Format("[{0}] {1}", mailMessage, e.Error));
    }
    else
    {
        Log.Info("Message sent.");
    }
    mailMessage.Dispose();
}

Disposing the MailMessage after the client.SendAsync(...) throws an exception. I need to dispose it in the Callback handler.

도움이 되었습니까?

해결책

This looks correct.

Note that MailMessage does not override ToString, so your logs will simply say [MailMessage] Send cancelled.
You might want to use the Subject proeprty (or some other property) instead.

다른 팁

I think this could help

   client.SendCompleted += (s, e) => { client.Dispose(); message.Dispose(); };
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top