Sub topic 9
Spawned tasks: abort, detach, and JoinError
This chapter assumes you know basic Rust, async/await, tokio::spawn, and that dropping a future cancels it. Earlier chapters showed that dropping a future stops it at its next await point. Spawned tasks follow different rules.
Dropping a handle does not cancel the task
tokio::spawn hands the future to the runtime and returns a JoinHandle. The runtime now owns the future, so dropping the handle does not drop the future. The task keeps running, detached, until it finishes or the runtime shuts down.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(50)).await;
println!("detached task still ran");
});
drop(handle); // detaches, does not cancel
sleep(Duration::from_millis(200)).await;
}This differs from timeout and select!, where losing the race drops the future. If you wrap a JoinHandle in timeout, the timeout drops only the handle. The task goes on running in the background.
Cancelling with abort
JoinHandle::abort asks the runtime to cancel the task. The task is dropped at its next await point, so its local variables are dropped and their Drop code runs.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_secs(10)).await;
});
handle.abort();
let err = handle.await.unwrap_err();
assert!(err.is_cancelled());
println!("task was cancelled");
}abort returns immediately. It does not wait for the task to stop. To learn when cancellation has taken effect, await the handle.
Reading the JoinError
Awaiting a JoinHandle<T> gives Result<T, JoinError>. A JoinError means the task did not produce a value. There are two causes:
| Cause | Check | Typical trigger |
|---|---|---|
| Cancelled | `err.is_cancelled()` | `abort()` or runtime shutdown |
| Panicked | `err.is_panic()` | a panic inside the task |
A panic in a spawned task does not crash the program. It surfaces as a JoinError when you await the handle. You can recover the panic payload with err.into_panic().
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
panic!("boom");
});
match handle.await {
Ok(()) => println!("finished"),
Err(e) if e.is_cancelled() => println!("cancelled"),
Err(e) if e.is_panic() => println!("task panicked"),
Err(e) => println!("other error: {e}"),
}
}Abort has limits
- A task is cancelled only at an await point. A task stuck in a loop with no
.await, or in blocking code, will not stop. The blocking-code chapter covers this. - If the task has already finished,
abortdoes nothing. Awaiting the handle then returns the normalOkresult. - A task cannot clean up asynchronously on abort.
Dropruns synchronously, so you cannot.awaitinside it. - Aborting a task that is holding a non-cancel-safe operation, such as half of a multi-step write, can leave state inconsistent.
Abort on drop
Sometimes you want a task tied to its owner's lifetime. Tokio's JoinHandle does not abort on drop, but you can get that with AbortHandle, JoinSet, or a small wrapper. JoinSet aborts all of its remaining tasks when it is dropped.
use std::time::Duration;
use tokio::{task::JoinSet, time::sleep};
#[tokio::main]
async fn main() {
let mut set = JoinSet::new();
for id in 0..3 {
set.spawn(async move {
sleep(Duration::from_secs(10)).await;
id
});
}
drop(set); // all three tasks are aborted
println!("set dropped");
}Summary of the three outcomes
- Drop the
JoinHandle: the task is detached and keeps running. - Call
abort(): the task is dropped at its next await point. - Await the handle: you get the value, or a
JoinErrorfor cancellation or panic.
Exercise
You wrap a spawned task's JoinHandle in tokio::time::timeout, and the timeout fires. Is the task cancelled? What should you do if you want it stopped?
Show answer
No. The timeout drops only the JoinHandle, which detaches the task, so it keeps running. To stop it, call abort() on the handle (for example through an AbortHandle cloned beforehand, or by passing &mut handle to timeout so you still own it afterwards), or use a CancellationToken.
Exercise
After handle.abort(), handle.await returns Ok(value). How is that possible?
Show answer
The task had already finished before the abort took effect, so abort had nothing to cancel and the task's normal result is returned.