CancellationToken and async requests

Cancellation is a signal the operation must observe. Passing a token to async I/O lets the caller request that work stop.

Time cooperativeSpace O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

The caller owns the CancellationTokenSource and passes its token to the operation. Calling Cancel sends a cooperative signal. HttpClient observes the token and ends the request by throwing OperationCanceledException; the task then completes as cancelled.

Code

using var cts = new CancellationTokenSource();
Task<string> task = GetDataAsync(cts.Token);
cts.Cancel(); // signal cancellation while the request is running
try { await task; } catch (OperationCanceledException) { /* expected here */ }

static async Task<string> GetDataAsync(CancellationToken token) {
    try {
        return await httpClient.GetStringAsync(url, token);
    }
    catch (OperationCanceledException) {
        Console.WriteLine("Request cancelled");
        throw;
    }
}
public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> task = pool.submit(Main::getData);
        task.cancel(true); // signal cancellation (interrupt) while the request is running
        try { task.get(); } catch (CancellationException e) { /* expected here */ }
        pool.shutdown();
    }

    static String getData() throws InterruptedException {
        try {
            return httpGetString(url);
        }
        catch (InterruptedException e) {
            System.out.println("Request cancelled");
            throw e;
        }
    }
}
struct OperationCanceled : exception {};

string getData(const atomic<bool>& cancelled) {
    try {
        return httpGetString(url, cancelled);   // throws OperationCanceled once the flag is set
    }
    catch (const OperationCanceled&) {
        cout << "Request cancelled\n";
        throw;
    }
}

int main() {
    atomic<bool> cancelled{false};   // C++17 has no CancellationToken: share a flag
    future<string> task = async(launch::async, getData, cref(cancelled));
    cancelled = true; // signal cancellation while the request is running
    try { task.get(); } catch (const OperationCanceled&) { /* expected here */ }
}
import asyncio

async def main() -> None:
    task = asyncio.create_task(get_data())
    task.cancel()  # signal cancellation while the request is running
    try:
        await task
    except asyncio.CancelledError:
        pass  # expected here

async def get_data() -> str:
    try:
        return await http_get_string(url)
    except asyncio.CancelledError:
        print("Request cancelled")
        raise

Tips

In the .NET library

ASP.NET Core supplies a request-aborted token for incoming requests. Passing it to database and HTTP calls can stop unnecessary work when the client disconnects.