From 2f2a2a335bd88762f09a0d75fcbd02be2c1d8021 Mon Sep 17 00:00:00 2001 From: LukeMathWalker <20745048+LukeMathWalker@users.noreply.github.com> Date: Thu, 16 May 2024 12:43:05 +0200 Subject: [PATCH] Explain how to cancel a spawned future. --- book/src/08_futures/07_cancellation.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/book/src/08_futures/07_cancellation.md b/book/src/08_futures/07_cancellation.md index 4b98c26..557aa72 100644 --- a/book/src/08_futures/07_cancellation.md +++ b/book/src/08_futures/07_cancellation.md @@ -84,6 +84,20 @@ clean-up work. This can be by: The optimal choice is contextual. +## Cancelling spawned tasks + +When you spawn a task using `tokio::spawn`, you can no longer drop it; +it belongs to the runtime. +Nonetheless, you can use its `JoinHandle` to cancel it if needed: + +```rust +async fn run() { + let handle = tokio::spawn(/* some async task */); + // Cancel the spawned task + handle.abort(); +} +``` + ## Further reading - Be extremely careful when using `tokio`'s `select!` macro to "race" two different futures. -- 2.45.2