pub struct CancellationToken { /* private fields */ }Expand description
Token for checking, waiting on, and triggering cancellation.
§Example
ⓘ
// Create a token
let token = CancellationToken::new();
// Clone to pass to other threads/tasks
let token2 = token.clone();
// Check if cancelled (fast, lock-free)
if token.is_cancelled() {
return Err("operation cancelled");
}
// Trigger cancellation
token.cancel();
// Block until cancelled (sync)
token.wait();
// Wait with timeout
if !token.wait_timeout(Duration::from_secs(5)) {
println!("timed out waiting for cancellation");
}
// Await cancellation (async)
token.cancelled().await;Implementations§
Source§impl CancellationToken
impl CancellationToken
Sourcepub fn new_with_timeout(timeout: Duration) -> Self
pub fn new_with_timeout(timeout: Duration) -> Self
Create a new cancellation token with automatic timeout.
Important: The timeout does NOT start immediately. It only
starts when the token is passed to a runtime function
(call_function, etc.). This allows you to create the token
ahead of time without the clock ticking.
Sourcepub fn is_cancelled(&self) -> bool
pub fn is_cancelled(&self) -> bool
Check if cancelled.
This is a lock-free atomic read, extremely fast for polling.
Sourcepub fn cancel(&self)
pub fn cancel(&self)
Trigger cancellation.
Safe to call multiple times - only the first call has effect. All waiters (sync and async) will be notified.
Sourcepub fn wait(&self)
pub fn wait(&self)
Block the current thread until cancellation occurs.
If already cancelled, returns immediately.
Sourcepub fn wait_timeout(&self, timeout: Duration) -> bool
pub fn wait_timeout(&self, timeout: Duration) -> bool
Block until cancelled or timeout expires.
Returns true if cancelled, false if the timeout elapsed first.
Trait Implementations§
Source§impl Clone for CancellationToken
impl Clone for CancellationToken
Source§fn clone(&self) -> CancellationToken
fn clone(&self) -> CancellationToken
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl Debug for CancellationToken
impl Debug for CancellationToken
Auto Trait Implementations§
impl Freeze for CancellationToken
impl RefUnwindSafe for CancellationToken
impl Send for CancellationToken
impl Sync for CancellationToken
impl Unpin for CancellationToken
impl UnwindSafe for CancellationToken
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more