Expand description
§enough-tokio
Bridge tokio’s CancellationToken to the Stop trait.
§When to Use
Use this crate when you have:
- Tokio async code that needs to cancel CPU-intensive sync work in
spawn_blocking - Libraries that accept
impl Stopand you want to use tokio’s cancellation
§Complete Example
use enough_tokio::TokioStop;
use enough::Stop;
use tokio_util::sync::CancellationToken;
#[tokio::main]
async fn main() {
let token = CancellationToken::new();
let stop = TokioStop::new(token.clone());
// Spawn CPU-intensive work
let handle = tokio::task::spawn_blocking(move || {
for i in 0..1_000_000 {
if i % 1000 == 0 && stop.should_stop() {
return Err("cancelled");
}
// ... do work ...
}
Ok("done")
});
// Cancel after timeout
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
token.cancel();
let result = handle.await.unwrap();
println!("{:?}", result);
}§Quick Reference
let token = CancellationToken::new();
let stop = TokioStop::new(token.clone());
stop.should_stop(); // Check if cancelled (sync)
stop.cancel(); // Trigger cancellation
// stop.cancelled().await; // Wait for cancellation (async)
let child = stop.child(); // Create child tokenStructs§
- Tokio
Stop - Wrapper around tokio’s
CancellationTokenthat implementsStop.
Traits§
- Cancellation
Token Stop Ext - Extension trait for CancellationToken to easily convert to Stop.