Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Implementation of SendMailAsync that correctly cancels the operation when CacellationToken is cancelled.
public async Task SendMailAsync(MailMessage message, CancellationToken ct)
{
try
{
var task = _smtpClient.SendMailAsync(message);
using (ct.Register(_smtpClient.SendAsyncCancel))
{
try
{
await task;
}
catch (OperationCanceledException exception)
{
if (exception.CancellationToken == ct)
{
Trace.TraceWarning("Operation has been canceled.");
return;
}
throw;
}
}
}
catch (Exception exception)
{
Trace.TraceError("Unexpected exception occured; Exception details: {0}", exception.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment