Click here to Skip to main content
14,111,188 members
Click here to Skip to main content
Add your own
alternative version

Stats

6.3K views
3 bookmarked
Posted 2 Aug 2017
Licenced CPOL

SmtpClient.SendMailAsync: CancellationToken Support

, 2 Aug 2017
Rate this:
Please Sign up or sign in to vote.
Adding cancellation support to the SendMailAsync method

Introduction

Since .NET 4.5, the SmtpClient class has provided the TPL-friendly SendMailAsync method to make it easier to send email asynchronously from an async method. Unfortunately, none of the overloads support passing a CancellationToken, which makes it tricky to cancel the operation.

I ran into this shortcoming recently with an asynchronous ASP.NET MVC action configured to cancel when the user disconnected. If that happened whilst an email was being sent, the application would log an exception with the message: "An asynchronous module or handler completed while an asynchronous operation was still pending". This was because the action was being cancelled, but the task to send the email was not.

Using the Code

The following extension method adds support for passing a CancellationToken. When canceled, it will call the SendAsyncCancel method to cancel the operation.

using System;
using System.ComponentModel;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;

namespace System.Net.Mail
{
    /// <summary>
    /// Extension methods for the <see cref="SmtpClient"/> class.
    /// </summary>
    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 = (sender, 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);
                        }
                    }
                }
            };

            client.SendCompleted += handler;

            try
            {
                client.SendAsync(message, tcs);
                registration = cancellationToken.Register(client.SendAsyncCancel);
            }
            catch
            {
                client.SendCompleted -= handler;
                registration.Dispose();
                throw;
            }

            return tcs.Task;
        }
    }
}

Using it is fairly simple:

using (var message = new MailMessage())
{
    InitializeMessage(message);
    
    var cts = new CancellationTokenSource();
    cts.CancelAfter(TimeSpan.FromSeconds(2));
    
    var smtp = new SmtpClient();
    await smtp.SendMailAsync(message, cts.Token).ConfigureAwait(false);
}

Points of Interest

There are various simpler versions of this method around - for example, this one posted in 2016 by Matt Benic. However, I wanted to keep the code as close as possible to the source of the existing method.

As pointed out by Todd Aspeotis in the comments to Matt's version, it's necessary to call SendAsync before registering the callback on the CancellationToken; otherwise, if the token is already cancelled, the SendAsyncCancel method will be called too soon.

History

  • 2017-08-02: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Richard Deeming
Software Developer Nevalee Business Solutions
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

 
SuggestionConfigureAwait Pin
hedidin3-Aug-17 8:41
professionalhedidin3-Aug-17 8:41 
PraiseRe: ConfigureAwait Pin
Richard Deeming3-Aug-17 9:56
mveRichard Deeming3-Aug-17 9:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190518.1 | Last Updated 2 Aug 2017
Article Copyright 2017 by Richard Deeming
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid