Search code examples
c#.nettask-parallel-libraryasync-await

How to transform task.Wait(CancellationToken) to an await statement?


So, task.Wait() can be transformed to await task. The semantics are different, of course, but this is roughly how I would go about transforming a blocking code with Waits to an asynchronous code with awaits.

My question is how to transform task.Wait(CancellationToken) to the respective await statement?


Solution

  • To create a new Task that represents an existing task but with an additional cancellation token is quite straightforward. You only need to call ContinueWith on the task, use the new token, and propagate the result/exceptions in the body of the continuation.

    public static Task WithCancellation(this Task task,
        CancellationToken token)
    {
        return task.ContinueWith(t => t.GetAwaiter().GetResult(), token);
    }
    public static Task<T> WithCancellation<T>(this Task<T> task,
        CancellationToken token)
    {
        return task.ContinueWith(t => t.GetAwaiter().GetResult(), token);
    }
    

    This allows you to write task.WithCancellation(cancellationToken) to add a token to a task, which you can then await.