tags:

views:

54

answers:

1

I don't know if this is the way it should be done:

{
...
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 error. So I need to dispose it in the Callback handler.

+1  A: 

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.

SLaks
I was mislead because of this example from msdn http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx where they dispose the mailMessage in the main function and not in the Callback.
Lieven Cardoen
@Lieven Cardoen, reason is, the example use a console and wait for the user input
Fredou
Ok, thx for the ToString comment.
Lieven Cardoen
Yes, but if you quickly press any key, you could get the same error as me, no? Maybe I'm missing something.
Lieven Cardoen
That example is wrong.
SLaks
Yes. It IS wrong. So many of MSDN's examples are WRONG WRONG WRONG WRONG WRONG WRONG WRONG GOD DAM F*(ÎNG WRONG
lucifer
You would think they they would know how to code in THEIR OWN LANGUAGE... wouldn't you?
lucifer