pub trait AsyncRuntime: Send + Sync {
// Required methods
fn spawn(
&self,
f: Pin<Box<dyn Future<Output = ()> + Send>>,
) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn Error + Send>>> + Send>>;
fn sleep(
&self,
duration: Duration,
) -> Pin<Box<dyn Future<Output = ()> + Send>>;
fn yield_now(&self) -> Pin<Box<dyn Future<Output = ()> + Send>>;
}Expand description
An Asynchronous Runtime.
This trait defines the various
Required Methods§
Sourcefn spawn(
&self,
f: Pin<Box<dyn Future<Output = ()> + Send>>,
) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn Error + Send>>> + Send>>
fn spawn( &self, f: Pin<Box<dyn Future<Output = ()> + Send>>, ) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn Error + Send>>> + Send>>
Spawn a task that executes a given future and returns the output.
§Arguments
f- A future representing the task to be spawned. This future cannot capture any variables from its environment by reference, as it will be executed in a different thread or context.
§Returns
A future which can be awaited to block until the task has completed.
§Examples
use typespec_client_core::async_runtime::get_async_runtime;
let async_runtime = get_async_runtime();
let handle = async_runtime.spawn(Box::pin(async {
// Simulate some work
std::thread::sleep(std::time::Duration::from_secs(1));
}));
handle.await.expect("Task should complete successfully");§Notes
This trait intentionally does not use the async_trait macro because when the
async_trait attribute is applied to a trait implementation, the rewritten
method cannot directly return a future, instead they wrap the return value
in a future, and we want the spawn method to directly return a future
that can be awaited.