Explain how to cancel a spawned future.

This commit is contained in:
LukeMathWalker 2024-05-16 12:43:05 +02:00
parent 73e7ddf913
commit 2f2a2a335b
1 changed files with 14 additions and 0 deletions

View File

@ -84,6 +84,20 @@ clean-up work. This can be by:
The optimal choice is contextual. The optimal choice is contextual.
## Cancelling spawned tasks
When you spawn a task using `tokio::spawn`, you can no longer drop it;
it belongs to the runtime.
Nonetheless, you can use its `JoinHandle` to cancel it if needed:
```rust
async fn run() {
let handle = tokio::spawn(/* some async task */);
// Cancel the spawned task
handle.abort();
}
```
## Further reading ## Further reading
- Be extremely careful when using `tokio`'s `select!` macro to "race" two different futures. - Be extremely careful when using `tokio`'s `select!` macro to "race" two different futures.