Skip to main content
Log in

Mojo struct

Task

struct Task[type: AnyType, origins: origin.set]

Represents an asynchronous task that will produce a value of the specified type.

A Task encapsulates a coroutine that is executing asynchronously and will eventually produce a result. Tasks can be awaited in async functions or waited on in synchronous code.

Parameters

  • type (AnyType): The type of value that this task will produce when completed.
  • origins (origin.set): The set of origins for the coroutine wrapped by this task.

Implemented traits

AnyType, UnknownDestructibility

Methods

__init__

@implicit __init__(out self, owned handle: Coroutine[type, origins])

Initialize a task with a coroutine.

Takes ownership of the provided coroutine and sets up the task to receive its result when completed.

Args:

  • handle (Coroutine[type, origins]): The coroutine to execute as a task. Ownership is transferred.

__del__

__del__(owned self)

Destroy the memory associated with a task. This must be manually called when a task goes out of scope.

__await__

__await__(self) -> ref [*[0,0]._result] type

Suspend the current async function until the task completes and its result becomes available. This function must be force inlined into the calling async function.

This method enables the use of the 'await' keyword with Task objects in async functions.

Returns:

A reference to the result value produced by the task.

get

get(self) -> ref [*[0,0]._result] type

Get the task's result value. Calling this on an incomplete task is undefined behavior.

Returns:

A reference to the result value produced by the task.

wait

wait(self) -> ref [*[0,0]._result] type

Block the current thread until the future value becomes available.

This method is used in synchronous code to wait for an asynchronous task to complete. Unlike __await__, this method does not suspend the current coroutine but instead blocks the entire thread.

Returns:

A reference to the result value produced by the task.