-
-
Save RichardD2/27ce7cfd57bc5e3f2b904a8cdc855a5a to your computer and use it in GitHub Desktop.
Extension method to have SmtpClient's SendMailAsync respond to a CancellationToken
This file contains 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
using System; | |
using System.ComponentModel; | |
using System.Net.Mail; | |
using System.Threading; | |
using System.Threading.Tasks; | |
public static class SmtpClientExtensions | |
{ | |
/// <summary> | |
/// Sends the specified message to an SMTP server for delivery as an asynchronous operation. | |
/// </summary> | |
/// <param name="client"> | |
/// The <see cref="SmtpClient"/> instance. | |
/// </param> | |
/// <param name="message"> | |
/// The <see cref="MailMessage"/> to send. | |
/// </param> | |
/// <param name="cancellationToken"> | |
/// The <see cref="CancellationToken"/> to monitor for cancellation requests. | |
/// </para> | |
/// <returns> | |
/// A <see cref="Task"/> representing the asynchronous operation. | |
/// </returns> | |
/// <exception cref="ArgumentNullException"> | |
/// <para><paramref name="client"/> is <see langword="null"/>.</para> | |
/// <para>-or-</para> | |
/// <para><paramref name="message"/> is <see langword="null"/>.</para> | |
/// </exception> | |
public static Task SendMailAsync(this SmtpClient client, MailMessage message, CancellationToken cancellationToken) | |
{ | |
if (client == null) throw new ArgumentNullException(nameof(client)); | |
if (message == null) throw new ArgumentNullException(nameof(message)); | |
if (!cancellationToken.CanBeCanceled) return client.SendMailAsync(message); | |
var tcs = new TaskCompletionSource<object>(); | |
var registration = default(CancellationTokenRegistration); | |
SendCompletedEventHandler handler = null; | |
handler = SendCompleted; | |
client.SendCompleted += handler; | |
try | |
{ | |
client.SendAsync(message, tcs); | |
registration = cancellationToken.Register(client.SendAsyncCancel); | |
} | |
catch | |
{ | |
client.SendCompleted -= handler; | |
registration.Dispose(); | |
throw; | |
} | |
return tcs.Task; | |
void SendCompleted(object sender, AsyncCompletedEventArgs e) | |
{ | |
if (e.UserState == tcs) | |
{ | |
try | |
{ | |
if (handler != null) | |
{ | |
client.SendCompleted -= handler; | |
handler = null; | |
} | |
} | |
finally | |
{ | |
registration.Dispose(); | |
if (e.Error != null) | |
{ | |
tcs.TrySetException(e.Error); | |
} | |
else if (e.Cancelled) | |
{ | |
tcs.TrySetCanceled(); | |
} | |
else | |
{ | |
tcs.TrySetResult(null); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This should really be baked in to the BCL.
UserVoice suggestion