pub struct JoinHandle<T> { /* private fields */ }Expand description
An owned permission to join on a task (awaiting its termination).
This can be thought of as the equivalent of
std::thread::JoinHandle or tokio::task::JoinHandle for
a task that is executed concurrently.
A JoinHandle detaches the associated task when it is dropped, which
means that there is no longer any handle to the task, and no way to join
on it.
This struct is created by the spawn and spawn_blocking
functions.
§Examples
Creation from spawn:
use tokio_with_wasm as tokio;
use tokio::spawn;
let join_handle: tokio::task::JoinHandle<_> = spawn(async {
// some work here
});Creation from spawn_blocking:
use tokio_with_wasm as tokio;
use tokio::task::spawn_blocking;
let join_handle: tokio::task::JoinHandle<_> = spawn_blocking(|| {
// some blocking work here
});Child being detached and outliving its parent:
use tokio_with_wasm as tokio;
use tokio::spawn;
let original_task = spawn(async {
let _detached_task = spawn(async {
// Here we sleep to make sure that the first task returns before.
// Assume that code takes a few seconds to execute here.
// This will be called, even though the JoinHandle is dropped.
println!("♫ Still alive ♫");
});
});
original_task.await;
println!("Original task is joined.");Implementations§
Source§impl<T> JoinHandle<T>
impl<T> JoinHandle<T>
Sourcepub fn abort(&self)
pub fn abort(&self)
Abort the task associated with the handle.
Awaiting a cancelled task might complete as usual if the task was
already completed at the time it was cancelled, but most likely it
will fail with a cancelled JoinError.
Be aware that tasks spawned using spawn_blocking cannot be aborted
because they are not async. If you call abort on a spawn_blocking
task, then this will not have any effect, and the task will continue
running normally. The exception is if the task has not started running
yet; in that case, calling abort may prevent the task from starting.
use tokio_with_wasm as tokio;
use tokio::time;
let mut handles = Vec::new();
handles.push(tokio::spawn(async {
time::sleep(time::Duration::from_secs(10)).await;
true
}));
handles.push(tokio::spawn(async {
time::sleep(time::Duration::from_secs(10)).await;
false
}));
for handle in &handles {
handle.abort();
}
for handle in handles {
assert!(handle.await.unwrap_err().is_cancelled());
}Sourcepub fn is_finished(&self) -> bool
pub fn is_finished(&self) -> bool
Checks if the task associated with this JoinHandle has finished.
Please note that this method can return false even if [abort] has been
called on the task. This is because the cancellation process may take
some time, and this method does not return true until it has
completed.
Sourcepub fn abort_handle(&self) -> AbortHandle
pub fn abort_handle(&self) -> AbortHandle
Returns a new AbortHandle that can be used to remotely abort this task.