Skip to main content

TaskHandle

Struct TaskHandle 

Source
pub struct TaskHandle<T> { /* private fields */ }
Expand description

A handle to a spawned task that can be used to await its result.

TaskHandle<T> is returned by Scope::spawn() and related methods. It provides:

  • The task ID for identification and debugging
  • A way to await the task’s result via join()

§Ownership

The TaskHandle does not own the task - the task is owned by its region. If the TaskHandle is dropped, the task continues running. The handle is just a way to observe the result.

§Cancel Safety

If join() is cancelled (the future is dropped before completion), the task is automatically aborted. This prevents orphan tasks in races and timeouts. The handle can be retried to await the cancellation result.

§Example

let handle = scope.spawn(&mut state, cx, async { 42 });
let result = handle.join(cx).await?;
assert_eq!(result, 42);

Implementations§

Source§

impl<T> TaskHandle<T>

Source

pub fn task_id(&self) -> TaskId

Returns the task ID of the spawned task.

Source

pub fn is_finished(&self) -> bool

Returns true if the task has reached a terminal join state.

This is true when either:

  • the result value is ready, or
  • the join channel is already closed.

The closed-channel case matters for drop semantics: dropping an unpolled join future should not stamp an abort reason onto a task that has already terminated and closed its join channel.

Source

pub fn join<'a>(&'a mut self, _cx: &'a Cx) -> JoinFuture<'a, T>

Waits for the task to complete and returns its result.

This method yields until the spawned task completes, then returns its output value.

§Errors

Returns Err(JoinError::Cancelled) if the task was cancelled. Returns Err(JoinError::Panicked) if the task panicked.

§Cancel Safety

If this method is cancelled (the returned future is dropped), the task is automatically aborted. This ensures that “stopping waiting” translates to “stopping the task”, preventing orphan tasks in races and timeouts.

§Example
let mut handle = scope.spawn(&mut state, cx, async { 42 });
match handle.join(cx).await {
    Ok(value) => println!("Task returned: {value}"),
    Err(JoinError::Cancelled(r)) => println!("Task was cancelled: {r}"),
    Err(JoinError::Panicked(p)) => println!("Task panicked: {p}"),
}
Source

pub fn join_with_drop_reason<'a>( &'a mut self, _cx: &'a Cx, reason: CancelReason, ) -> JoinFuture<'a, T>

Waits for the task to complete, aborting with a specific reason if dropped.

This is like join(), but allows specifying the cancellation reason that should be used if the join future is dropped before completion. This is useful for combinators like race that want to attribute cancellation to “losing the race”.

Source

pub fn try_join(&mut self) -> Result<Option<T>, JoinError>

Attempts to get the task’s result without waiting.

§Returns
  • Ok(Some(result)) if the task has completed
  • Ok(None) if the task is still running
  • Err(JoinError) if the task was cancelled or panicked
  • Err(JoinError::PolledAfterCompletion) if a terminal result was already consumed
Source

pub fn abort(&self)

Aborts the task (requests cancellation).

This is a request - the task may not stop immediately. The task will observe the cancellation at its next checkpoint.

Source

pub fn abort_with_reason(&self, reason: CancelReason)

Aborts the task (requests cancellation) with an explicit reason.

If a reason is already present, this request strengthens it using CancelReason::strengthen, preserving deterministic attribution.

Trait Implementations§

Source§

impl<T: Debug> Debug for TaskHandle<T>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for TaskHandle<T>

§

impl<T> !RefUnwindSafe for TaskHandle<T>

§

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

§

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

§

impl<T> Unpin for TaskHandle<T>

§

impl<T> UnsafeUnpin for TaskHandle<T>

§

impl<T> !UnwindSafe for TaskHandle<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> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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<T> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more