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...
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With