Reviewing the MSDN docs for SmtpClient, I noticed that the example code looks like this:
client.SendAsync(message, userState);
// More stuff
message.Dispose();
The call to SendAsync could take significant time to complete. How is it that message remains in a useful state if it is disposed on the line following the SendAsync call?
Further, SmtpClient implements IDisposable. The MSDN example should more property be formed like
using (SmtpClient client = new SmtpClient())
{
// Initialize client and create the message
using (MailMessage message = new MailMessage(from, to))
{
client.SendAsync(message, userState);
// More stuff
}
}
So not only would message.Dispose() be called while client.SendAsync() is potentially still executing, but client.Dispose() would be called as well.
How is it that client remains in a useful state for the completion of SendAsync() if Dispose() is called almost immediately after the call to SendAsync()?
Or, is the MSDN example just wrong?
You should dispose it only after async send operation completed or canceled.
So dispose it in this situation in SendCompleted event handler
Look at sample in MSDN:
http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx
Or this blog post
http://leedumond.com/blog/new-in-net-4-dont-forget-to-dispose-your-smtpclient-instances/
Example on MSDN is bad. And you are not the first person with this problem look at comments there: