pub trait AsyncRuntime: Send + Sync {
// Required methods
fn spawn(
&self,
f: Pin<Box<dyn Future<Output = ()> + Send>>,
) -> Pin<Box<dyn AbortableTask<Output = Result<(), Box<dyn Error + 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 abstracts task spawning, sleeping, and yielding so that library code can remain runtime-agnostic.
Required Methods§
Sourcefn spawn(
&self,
f: Pin<Box<dyn Future<Output = ()> + Send>>,
) -> Pin<Box<dyn AbortableTask<Output = Result<(), Box<dyn Error + Send>>>>>
fn spawn( &self, f: Pin<Box<dyn Future<Output = ()> + Send>>, ) -> Pin<Box<dyn AbortableTask<Output = Result<(), Box<dyn Error + 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.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".