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.
It is designed for !Send / single-threaded async environments (e.g., futures::executor::LocalPool).
Features
- Create a
CancellationTokenSourceto control cancellation. - Generate
CancellationTokens to be passed to tasks. - Async-aware:
token.cancelled().awaitcompletes when the token is cancelled. - Supports registering callbacks that execute on cancellation.
- Fully
Cloneable and works withRc/Cell/RefCell.
⚠️ This crate is not thread-safe. Use only in single-threaded async contexts.
Installation
Add this to your Cargo.toml:
[]
= "0.1"
Usage
use ;
use ;
use Delay;
use Duration;
let cts = new;
let token = cts.token;
let mut pool = new;
let spawner = pool.spawner;
spawner.spawn_local.unwrap;
// Cancel after 1 second
spawner.spawn_local.unwrap;
pool.run;
API
- CancellationTokenSource::new() – create a new source.
- token() – get a CancellationToken.
- cancel() – cancel all tasks associated with this source.
- is_cancelled() – check if already cancelled.
- CancellationToken::cancelled() – returns a Future that resolves on cancellation.
- CancellationToken::register(f) – register a callback for cancellation.
License
Apache-2.0