Search code examples
c#asynchronousdisposeusing-statement

Using-statement with async call | Cancel operation?


I'm facing a general question where I can't find a good example to try-it-for-myself. Google isn't a help neither.

Imagine a structure like this:

MailMessage mail = new MailMessage(sender, receiver);
using(SmtpClient client = new SmtpClient())
{
    client.Host ...
    client.Port ...

    mail.subject ...
    mail.body ...

    client.SendAsync(mail);
}

What if the server is slow and takes a while to accept the mail. Is it possible that the SmtpClient is disposed before the operation is done? Will it be canceled or broken in any way?

Is there a general answer for this? The servers in here are too fast, don't know how to do a try-out.


If thinking about canceling a BackgroundWorker it's always finishing the current operation. Could be the same here, or maybe not...


Solution

  • You can use the newer SendMailAsync method that returns a Task, and await that task:

    MailMessage mail = new MailMessage(sender, receiver);
    using(SmtpClient client = new SmtpClient())
    {
        client.Host ...
        client.Port ...
    
        mail.subject ...
        mail.body ...
    
        await client.SendMailAsync(mail);
    }
    

    This will ensure that the client isn't disposed before SendMailAsync completes.

    (of course, this means your method now has to be async as well)