Struct CancellationToken

pub struct CancellationToken { /* private fields */ }

A token which can be used to signal a cancellation request to one or more tasks.

Tasks can call [CancellationToken::cancelled()] in order to obtain a Future which will be resolved when cancellation is requested.

Cancellation can be requested through the CancellationToken::cancel method.

Examples

use tokio::select;
use tokio_util::sync::CancellationToken;

#[tokio::main]
async fn main() {
    let token = CancellationToken::new();
    let cloned_token = token.clone();

    let join_handle = tokio::spawn(async move {
        // Wait for either cancellation or a very long time
        select! {
            _ = cloned_token.cancelled() => {
                // The token was cancelled
                5
            }
            _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
                99
            }
        }
    });

    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        token.cancel();
    });

    assert_eq!(5, join_handle.await.unwrap());
}

Implementations

impl CancellationToken

fn new() -> CancellationToken

Creates a new CancellationToken in the non-cancelled state.

fn child_token(&self) -> CancellationToken

Creates a CancellationToken which will get cancelled whenever the current token gets cancelled. Unlike a cloned CancellationToken, cancelling a child token does not cancel the parent token.

If the current token is already cancelled, the child token will get returned in cancelled state.

Examples

use tokio::select;
use tokio_util::sync::CancellationToken;

#[tokio::main]
async fn main() {
    let token = CancellationToken::new();
    let child_token = token.child_token();

    let join_handle = tokio::spawn(async move {
        // Wait for either cancellation or a very long time
        select! {
            _ = child_token.cancelled() => {
                // The token was cancelled
                5
            }
            _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
                99
            }
        }
    });

    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        token.cancel();
    });

    assert_eq!(5, join_handle.await.unwrap());
}
fn cancel(&self)

Cancel the CancellationToken and all child tokens which had been derived from it.

This will wake up all tasks which are waiting for cancellation.

Be aware that cancellation is not an atomic operation. It is possible for another thread running in parallel with a call to cancel to first receive true from is_cancelled on one child node, and then receive false from is_cancelled on another child node. However, once the call to cancel returns, all child nodes have been fully cancelled.

fn is_cancelled(&self) -> bool

Returns true if the CancellationToken is cancelled.

fn cancelled(&self) -> WaitForCancellationFuture<'_>

Returns a Future that gets fulfilled when cancellation is requested.

Equivalent to:

async fn cancelled(&self);

The future will complete immediately if the token is already cancelled when this method is called.

Cancellation safety

This method is cancel safe.

fn cancelled_owned(self) -> WaitForCancellationFutureOwned

Returns a Future that gets fulfilled when cancellation is requested.

Equivalent to:

async fn cancelled_owned(self);

The future will complete immediately if the token is already cancelled when this method is called.

The function takes self by value and returns a future that owns the token.

Cancellation safety

This method is cancel safe.

fn drop_guard(self) -> DropGuard

Creates a DropGuard for this token.

Returned guard will cancel this token (and all its children) on drop unless disarmed.

fn drop_guard_ref(&self) -> DropGuardRef<'_>

Creates a DropGuardRef for this token.

Returned guard will cancel this token (and all its children) on drop unless disarmed.

async fn run_until_cancelled<F>(&self, fut: F) -> Option<F::Output>
where
    F: Future,

Runs a future to completion and returns its result wrapped inside of an Option unless the CancellationToken is cancelled. In that case the function returns None and the future gets dropped.

Fairness

Calling this on an already-cancelled token directly returns None. For all subsequent polls, in case of concurrent completion and cancellation, this is biased towards the future completion.

Cancellation safety

This method is only cancel safe if fut is cancel safe.

async fn run_until_cancelled_owned<F>(self, fut: F) -> Option<F::Output>
where
    F: Future,

Runs a future to completion and returns its result wrapped inside of an Option unless the CancellationToken is cancelled. In that case the function returns None and the future gets dropped.

The function takes self by value and returns a future that owns the token.

Fairness

Calling this on an already-cancelled token directly returns None. For all subsequent polls, in case of concurrent completion and cancellation, this is biased towards the future completion.

Cancellation safety

This method is only cancel safe if fut is cancel safe.

Trait Implementations

impl Clone for CancellationToken

fn clone(&self) -> Self

Creates a clone of the CancellationToken which will get cancelled whenever the current token gets cancelled, and vice versa.

impl Debug for CancellationToken

fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl Default for CancellationToken

fn default() -> CancellationToken

impl Drop for CancellationToken

fn drop(&mut self)

impl Eq for CancellationToken

impl Hash for CancellationToken

fn hash<H: Hasher>(&self, state: &mut H)

impl PartialEq for CancellationToken

fn eq(&self, other: &CancellationToken) -> bool

Checks if two tokens are equal in terms of their cancellation operation.

Two tokens are considered equal if cancelling one will always also cancel the other and vice versa. This is only true for cloned tokens and not for tokens in a parent-child relationship.

impl RefUnwindSafe for CancellationToken

impl UnwindSafe for CancellationToken

Auto Trait Implementations

impl Freeze for CancellationToken

impl Send for CancellationToken

impl Sync for CancellationToken

impl Unpin for CancellationToken

impl UnsafeUnpin for CancellationToken

Blanket Implementations

impl<T> Any for CancellationToken where T: 'static + ?Sized,

fn type_id(&self) -> TypeId

impl<T> Borrow<T> for CancellationToken where T: ?Sized,

fn borrow(&self) -> &T

impl<T> BorrowMut<T> for CancellationToken where T: ?Sized,

fn borrow_mut(&mut self) -> &mut T

impl<T> CloneToUninit for CancellationToken where T: Clone,

unsafe fn clone_to_uninit(&self, dest: *mut u8)

impl<T> From<T> for CancellationToken

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> ToOwned for CancellationToken where T: Clone,

type Owned = T;
fn to_owned(&self) -> T
fn clone_into(&self, target: &mut T)

impl<T, U> Into<U> for CancellationToken where U: From<T>,

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom<U> for CancellationToken where U: Into<T>,

type Error = Infallible;
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto<U> for CancellationToken where U: TryFrom<T>,

type Error = <U as TryFrom<T>>::Error;
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>