Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 732
C4d Avatar asked Jun 14 '16 12:06

C4d


People also ask

How do I cancel async tasks?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

What happens when you call async method?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

What happens when you call async method without await C#?

However, just to address "Call an async method in C# without await", you can execute the async method inside a Task. Run . This approach will wait until MyAsyncMethod finish. await asynchronously unwraps the Result of your task, whereas just using Result would block until the task had completed.

Does await Block C#?

When the await operator is applied to the operand that represents an already completed operation, it returns the result of the operation immediately without suspension of the enclosing method. The await operator doesn't block the thread that evaluates the async method.


1 Answers

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)

like image 51
Thomas Levesque Avatar answered Oct 11 '22 12:10

Thomas Levesque