bevyengine / bevyengine/bevy

Calling .await inside async in AsyncComputeTaskPool.spawn() causes tokio panic

Open
#2,532 11 comments 0 reactions 0 assignees View on GitHub
A-Tasks C-Dependencies C-Usability S-Blocked
Dominant language
Rust
Stars
48.2k
Forks
4.8k
Avg merge
3d 22h
Merged PRs (30d)
161

Description

## Bevy version

0.5

## Operating system & version

Ubuntu 20.04

## What you did

Run the code
```
use bevy::{
prelude::*,
tasks::{AsyncComputeTaskPool, Task},
};
use futures_lite::future;
use rand::Rng;
use tokio::time::delay_for;
use std::time::{Duration, Instant};

fn main() {
let mut app = App::build();

app
.add_plugins(MinimalPlugins)
.add_system(spawn_tasks.system())
.add_system(handle_tasks.system())
.run();
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Result {
pub time: f32
}

fn spawn_tasks(mut commands: Commands, thread_pool: Res) {
let task = thread_pool.spawn(async move {
delay_for(Duration::from_millis(1000)).await;
Result { time: 1.0 }
});
commands.spawn().insert(task);
}

fn handle_tasks(
mut commands: Commands,
mut transform_tasks: Query<(Entity, &mut Task)>,
) {
for (entity, mut task) in transform_tasks.iter_mut() {
if let Some(res) = future::block_on(future::poll_once(&mut *task)) {
commands.entity(entity).remove::>();
}
}
}
```

## What you expected to happen

Should run with no panic

## What actually happened

Panics and shows this error
```
thread 'Async Compute Task Pool (3)' panicked at 'there is no timer running, must be called from the context of a Tokio 0.2.x runtime', .cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.25/src/time/driver/handle.rs:24:32
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'Async Compute Task Pool (2)' panicked at 'there is no timer running, must be called from the context of a Tokio 0.2.x runtime', .cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.25/src/time/driver/handle.rs:24:32
thread 'Async Compute Task Pool (1)' panicked at 'there is no timer running, must be called from the context of a Tokio 0.2.x runtime', .cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.25/src/time/driver/handle.rs:24:32
thread 'Async Compute Task Pool (0)' panicked at 'there is no timer running, must be called from the context of a Tokio 0.2.x runtime', .cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.25/src/time/driver/handle.rs:24:32
thread 'Compute Task Pool (7)' panicked at 'task has failed', .cargo/registry/src/github.com-1ecc6299db9ec823/async-task-4.0.3/src/task.rs:368:45
thread 'main' panicked at 'task has failed', .cargo/registry/src/github.com-1ecc6299db9ec823/async-task-4.0.3/src/task.rs:368:45

```

Bug confirmed with @ashneverdawn

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.