Skip to content

Instantly share code, notes, and snippets.

@tuan
Created February 6, 2016 22:14
Show Gist options
  • Save tuan/1dac97eea8846a76c900 to your computer and use it in GitHub Desktop.
Save tuan/1dac97eea8846a76c900 to your computer and use it in GitHub Desktop.
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