Search code examples
c#async-awaittaskcancellationcancellation-token

Concise way to await a canceled Task?


I find myself writing code like this a lot:

try
{
    cancellationTokenSource.Cancel();
    await task.ConfigureAwait(false); // this is the task that was cancelled
}
catch(OperationCanceledException)
{
    // Cancellation expected and requested
}

Given that I requested the cancellation, it is expected and I'd really like the exception to be ignored. This seems like a common case.

Is there a more concise way to do this? Have I missed something about cancellation? It seems like there should be a task.CancellationExpected() method or something.


Solution

  • I don't think there is anything built-in, but you could capture your logic in extension methods (one for Task, one for Task<T>):

    public static async Task IgnoreWhenCancelled(this Task task)
    {
        try
        {
            await task.ConfigureAwait(false);
        }
        catch (OperationCanceledException)
        {
        }
    }
    
    public static async Task<T> IgnoreWhenCancelled<T>(this Task<T> task)
    {
        try
        {
            return await task.ConfigureAwait(false);
        }
        catch (OperationCanceledException)
        {
            return default;
        }
    }
    

    Then you can write your code simpler:

    await task.IgnoreWhenCancelled();
    

    or

    var result = await task.IgnoreWhenCancelled();
    

    (You might still want to add .ConfigureAwait(false) depending on your synchronization needs.)