Using an Asynchronous Call Statement | Cancel operation?

Im facing a general question where I cannot find a good example to try this for myself. Google doesn't help either.

Imagine this structure:

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

What to do if the server is slow and takes some time to receive mail. Is it possible that SmtpClient is before the operation? Will it be destroyed or broken in any way?

Is there a general answer for this? The servers here are too fast, they don’t know how to do a survey.


If you are thinking of canceling BackgroundWorker , it always finishes the current operation. Maybe the same thing here, or maybe not ...

+7
c # asynchronous using-statement dispose
source share
1 answer

You can use the new SendMailAsync method, which returns Task , and waits for this 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 ensures that the client will not be deleted until SendMailAsync complete.

(of course, this means that your method should now be asynchronous)

+12
source share

All Articles