Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add convenience method for polling Task<> #4627

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion crates/bevy_tasks/src/task.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

/// Wraps `async_executor::Task`, a spawned future.
Expand Down Expand Up @@ -40,6 +40,25 @@ impl<T> Task<T> {
pub async fn cancel(self) -> Option<T> {
self.0.cancel().await
}

/// Check if the task has been completed, and if so, return the value.
pub fn check(&mut self) -> Option<T> {
const NOOP_WAKER_VTABLE: &RawWakerVTable = &RawWakerVTable::new(
|_| RawWaker::new(std::ptr::null::<()>(), NOOP_WAKER_VTABLE),
|_| {},
|_| {},
|_| {},
);

// SAFE: all vtable functions are always safe to call.
let waker =
unsafe { Waker::from_raw(RawWaker::new(std::ptr::null::<()>(), NOOP_WAKER_VTABLE)) };

match Pin::new(&mut self.0).poll(&mut Context::from_waker(&waker)) {
Poll::Ready(val) => Some(val),
Poll::Pending => None,
}
}
}

impl<T> Future for Task<T> {
Expand Down
3 changes: 1 addition & 2 deletions examples/async_tasks/async_compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use bevy::{
prelude::*,
tasks::{AsyncComputeTaskPool, Task},
};
use futures_lite::future;
use rand::Rng;
use std::time::{Duration, Instant};

Expand Down Expand Up @@ -86,7 +85,7 @@ fn handle_tasks(
box_material_handle: Res<BoxMaterialHandle>,
) {
for (entity, mut task) in transform_tasks.iter_mut() {
if let Some(transform) = future::block_on(future::poll_once(&mut task.0)) {
if let Some(transform) = task.0.check() {
// Add our new PbrBundle of components to our tagged entity
commands.entity(entity).insert_bundle(PbrBundle {
mesh: box_mesh_handle.clone(),
Expand Down