How to cancel multiple async tasks in Rust when one fails? #186326
-
BodyHi, I’m using Rust with Here’s my setup: use tokio::time::{sleep, Duration};
use tokio::task;
#[tokio::main]
async fn main() {
let tasks = vec![
task::spawn(async { sleep(Duration::from_secs(3)).await; Ok::<_, &str>("A done") }),
task::spawn(async { sleep(Duration::from_secs(1)).await; Err::<&str, _>("B failed") }),
task::spawn(async { sleep(Duration::from_secs(2)).await; Ok::<_, &str>("C done") }),
];
// How can I run all tasks and cancel the remaining ones if any fails?
}Right now, all tasks run to completion, but I want to stop any remaining tasks immediately when one returns an error. What’s the best way to handle this in Rust async? Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
Hi @shield178, could you clarify whether you want the remaining tasks to abort immediately mid-execution, or is it okay if they finish their current step first? |
Beta Was this translation helpful? Give feedback.
-
|
Hey @shield178! 😊 I think I understand the issue you’re facing. You want to run multiple async tasks, but stop any remaining ones as soon as one fails. A good way to do this in Rust with Tokio is to use Here’s a simple example: Explanation:
Tips:
Hope this helps! Let me know if you want me to show an example with tasks that panic or hold resources like files — it gets a bit trickier, but it’s doable. |
Beta Was this translation helpful? Give feedback.
Hey @shield178! 😊
I think I understand the issue you’re facing. You want to run multiple async tasks, but stop any remaining ones as soon as one fails. A good way to do this in Rust with Tokio is to use
futures::future::select_all.Here’s a simple example: