Struct JoinHandle

Source
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>

Source

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());
}
Source

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.

Source

pub fn abort_handle(&self) -> AbortHandle

Returns a new AbortHandle that can be used to remotely abort this task.

Trait Implementations§

Source§

impl<T> Debug for JoinHandle<T>
where T: Debug,

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<T> Future for JoinHandle<T>

Source§

type Output = Result<T, JoinError>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementations§

§

impl<T> Freeze for JoinHandle<T>

§

impl<T> RefUnwindSafe for JoinHandle<T>

§

impl<T> Send for JoinHandle<T>
where T: Send,

§

impl<T> Sync for JoinHandle<T>
where T: Send,

§

impl<T> Unpin for JoinHandle<T>

§

impl<T> UnwindSafe for JoinHandle<T>

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<F> IntoFuture for F
where F: Future,

Source§

type Output = <F as Future>::Output

The output that the future will produce on completion.
Source§

type IntoFuture = F

Which kind of future are we turning this into?
Source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
Source§

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

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.