Struct CancellationToken
struct CancellationToken { ... }
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() -> CancellationTokenCreates a new
CancellationTokenin the non-cancelled state.fn child_token(self: &Self) -> CancellationTokenCreates a
CancellationTokenwhich will get cancelled whenever the current token gets cancelled. Unlike a clonedCancellationToken, 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: &Self)Cancel the
CancellationTokenand 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
cancelto first receivetruefromis_cancelledon one child node, and then receivefalsefromis_cancelledon another child node. However, once the call tocancelreturns, all child nodes have been fully cancelled.fn is_cancelled(self: &Self) -> boolReturns
trueif theCancellationTokenis cancelled.fn cancelled(self: &Self) -> WaitForCancellationFuture<'_>Returns a
Futurethat gets fulfilled when cancellation is requested.The future will complete immediately if the token is already cancelled when this method is called.
Cancel safety
This method is cancel safe.
fn cancelled_owned(self: Self) -> WaitForCancellationFutureOwnedReturns a
Futurethat gets fulfilled when cancellation is requested.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.
Cancel safety
This method is cancel safe.
fn drop_guard(self: Self) -> DropGuardCreates a
DropGuardfor this token.Returned guard will cancel this token (and all its children) on drop unless disarmed.
async fn run_until_cancelled<F>(self: &Self, fut: F) -> Option<<F as >::Output> where F: FutureRuns a future to completion and returns its result wrapped inside of an
Optionunless theCancellationTokenis cancelled. In that case the function returnsNoneand the future gets dropped.Cancel safety
This method is only cancel safe if
futis cancel safe.async fn run_until_cancelled_owned<F>(self: Self, fut: F) -> Option<<F as >::Output> where F: FutureRuns a future to completion and returns its result wrapped inside of an
Optionunless theCancellationTokenis cancelled. In that case the function returnsNoneand the future gets dropped.The function takes self by value and returns a future that owns the token.
Cancel safety
This method is only cancel safe if
futis cancel safe.
impl Clone for CancellationToken
fn clone(self: &Self) -> SelfCreates a clone of the
CancellationTokenwhich will get cancelled whenever the current token gets cancelled, and vice versa.
impl Debug for CancellationToken
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Default for CancellationToken
fn default() -> CancellationToken
impl Drop for CancellationToken
fn drop(self: &mut Self)
impl Freeze for CancellationToken
impl RefUnwindSafe for CancellationToken
impl Send for CancellationToken
impl Sync for CancellationToken
impl Unpin for CancellationToken
impl UnsafeUnpin for CancellationToken
impl UnwindSafe for CancellationToken
impl<T> Any for CancellationToken
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for CancellationToken
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for CancellationToken
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for CancellationToken
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for CancellationToken
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for CancellationToken
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for CancellationToken
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for CancellationToken
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for CancellationToken
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>