Created
February 6, 2016 22:14
-
-
Save tuan/1dac97eea8846a76c900 to your computer and use it in GitHub Desktop.
Implementation of SendMailAsync that correctly cancels the operation when CacellationToken is cancelled.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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