Crate async_cancellation_token

Crate async_cancellation_token 

Source
Expand description

§async-cancellation-token

async-cancellation-token is a lightweight single-threaded Rust library that provides cancellation tokens for cooperative cancellation of asynchronous tasks and callbacks.

This crate is designed for single-threaded async environments such as futures::executor::LocalPool. It internally uses Rc, Cell, and RefCell, and is not thread-safe.

Features:

  • CancellationTokenSource can cancel multiple associated CancellationTokens.
  • CancellationToken can be awaited via .cancelled() or checked synchronously.
  • Supports registration of one-time callbacks (FnOnce) that run on cancellation.

§Example

use std::time::Duration;
use async_cancellation_token::CancellationTokenSource;
use futures::{FutureExt, executor::LocalPool, pin_mut, select, task::LocalSpawnExt};
use futures_timer::Delay;

let cts = CancellationTokenSource::new();
let token = cts.token();

let mut pool = LocalPool::new();
let spawner = pool.spawner();

// Spawn a task that performs 5 steps but can be cancelled
spawner.spawn_local(async move {
    for i in 1..=5 {
        let delay = Delay::new(Duration::from_millis(100)).fuse();
        let cancelled = token.cancelled().fuse();
        pin_mut!(delay, cancelled);

        select! {
            _ = delay => println!("Step {i}"),
            _ = cancelled => {
                println!("Cancelled!");
                break;
            }
        }
    }
}.map(|_| ())).unwrap();

// Cancel after 250ms
spawner.spawn_local(async move {
    Delay::new(Duration::from_millis(250)).await;
    cts.cancel();
}.map(|_| ())).unwrap();

pool.run();

Structs§

CancellationToken
A token that can be checked for cancellation or awaited.
CancellationTokenRegistration
Represents a registered callback on a CancellationToken.
CancellationTokenSource
A source that can cancel associated CancellationTokens.
Cancelled
Error returned when a cancelled token is checked synchronously.
CancelledFuture
A future that completes when a CancellationToken is cancelled.