pub trait Task:
Future
+ 'static
+ Send {
// Required methods
fn result(self) -> impl Future<Output = Result<Self::Output, Error>> + Send;
fn cancel(self);
}
Expand description
A handle to a spawned task that can be safely moved between threads.
This trait extends Future
, which means it can be awaited to get the result directly.
§Panics
If the task is cancelled or panics during execution, the attempt to await the task will panic.
If you need to handle these cases gracefully, use the [result
] method instead.
Required Methods§
Sourcefn result(self) -> impl Future<Output = Result<Self::Output, Error>> + Send
fn result(self) -> impl Future<Output = Result<Self::Output, Error>> + Send
Returns the task result or error without panicking.
Unlike directly awaiting the task, this method returns a Result
that
allows you to handle task panics and cancellation gracefully.
§Returns
Ok(T)
- Task completed successfullyErr(Error::Panicked(_))
- Task panicked during executionErr(Error::Cancelled)
- Task was cancelled
§Examples
use executor_core::{spawn, Error};
let task = spawn(async { 42 });
match task.result().await {
Ok(value) => println!("Result: {}", value),
Err(Error::Panicked(msg)) => eprintln!("Panic: {}", msg),
Err(Error::Cancelled) => println!("Cancelled"),
}
Sourcefn cancel(self)
fn cancel(self)
Cancels the task, preventing further execution.
After calling this method, the task will stop executing as soon as possible.
Any attempt to await the task or get its result will return Error::Cancelled
.
§Notes
- Cancellation is cooperative and may not be immediate
- Already completed tasks cannot be cancelled
§Examples
use executor_core::spawn;
use std::time::Duration;
let task = spawn(async {
tokio::time::sleep(Duration::from_secs(10)).await;
"Done"
});
// Cancel the long-running task
task.cancel();
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.