1use crate::{App, PlatformDispatcher, PlatformScheduler};
2use futures::channel::mpsc;
3use scheduler::Scheduler;
4use smol::prelude::*;
5use std::{
6 fmt::Debug,
7 future::Future,
8 marker::PhantomData,
9 mem,
10 pin::Pin,
11 rc::Rc,
12 sync::Arc,
13 time::{Duration, Instant},
14};
15use util::TryFutureExt;
16
17pub use scheduler::{FallibleTask, ForegroundExecutor as SchedulerForegroundExecutor, Priority};
18
19/// A pointer to the executor that is currently running,
20/// for spawning background tasks.
21#[derive(Clone)]
22pub struct BackgroundExecutor {
23 inner: scheduler::BackgroundExecutor,
24 dispatcher: Arc<dyn PlatformDispatcher>,
25}
26
27/// A pointer to the executor that is currently running,
28/// for spawning tasks on the main thread.
29#[derive(Clone)]
30pub struct ForegroundExecutor {
31 inner: scheduler::ForegroundExecutor,
32 dispatcher: Arc<dyn PlatformDispatcher>,
33 not_send: PhantomData<Rc<()>>,
34}
35
36/// Task is a primitive that allows work to happen in the background.
37///
38/// It implements [`Future`] so you can `.await` on it.
39///
40/// If you drop a task it will be cancelled immediately. Calling [`Task::detach`] allows
41/// the task to continue running, but with no way to return a value.
42#[must_use]
43#[derive(Debug)]
44pub struct Task<T>(scheduler::Task<T>);
45
46impl<T> Task<T> {
47 /// Creates a new task that will resolve with the value.
48 pub fn ready(val: T) -> Self {
49 Task(scheduler::Task::ready(val))
50 }
51
52 /// Returns true if the task has completed or was created with `Task::ready`.
53 pub fn is_ready(&self) -> bool {
54 self.0.is_ready()
55 }
56
57 /// Detaching a task runs it to completion in the background.
58 pub fn detach(self) {
59 self.0.detach()
60 }
61
62 /// Wraps a scheduler::Task.
63 pub fn from_scheduler(task: scheduler::Task<T>) -> Self {
64 Task(task)
65 }
66
67 /// Converts this task into a fallible task that returns `Option<T>`.
68 ///
69 /// Unlike the standard `Task<T>`, a [`FallibleTask`] will return `None`
70 /// if the task was cancelled.
71 ///
72 /// # Example
73 ///
74 /// ```ignore
75 /// // Background task that gracefully handles cancellation:
76 /// cx.background_spawn(async move {
77 /// let result = foreground_task.fallible().await;
78 /// if let Some(value) = result {
79 /// // Process the value
80 /// }
81 /// // If None, task was cancelled - just exit gracefully
82 /// }).detach();
83 /// ```
84 pub fn fallible(self) -> FallibleTask<T> {
85 self.0.fallible()
86 }
87}
88
89impl<T, E> Task<Result<T, E>>
90where
91 T: 'static,
92 E: 'static + Debug,
93{
94 /// Run the task to completion in the background and log any errors that occur.
95 #[track_caller]
96 pub fn detach_and_log_err(self, cx: &App) {
97 let location = core::panic::Location::caller();
98 cx.foreground_executor()
99 .spawn(self.log_tracked_err(*location))
100 .detach();
101 }
102}
103
104impl<T> std::future::Future for Task<T> {
105 type Output = T;
106
107 fn poll(
108 self: std::pin::Pin<&mut Self>,
109 cx: &mut std::task::Context<'_>,
110 ) -> std::task::Poll<Self::Output> {
111 // SAFETY: Task is a repr(transparent) wrapper around scheduler::Task,
112 // and we're just projecting the pin through to the inner task.
113 let inner = unsafe { self.map_unchecked_mut(|t| &mut t.0) };
114 inner.poll(cx)
115 }
116}
117
118impl BackgroundExecutor {
119 /// Creates a new BackgroundExecutor from the given PlatformDispatcher.
120 pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
121 #[cfg(any(test, feature = "test-support"))]
122 let scheduler: Arc<dyn Scheduler> = if let Some(test_dispatcher) = dispatcher.as_test() {
123 test_dispatcher.scheduler().clone()
124 } else {
125 Arc::new(PlatformScheduler::new(dispatcher.clone()))
126 };
127
128 #[cfg(not(any(test, feature = "test-support")))]
129 let scheduler: Arc<dyn Scheduler> = Arc::new(PlatformScheduler::new(dispatcher.clone()));
130
131 Self {
132 inner: scheduler::BackgroundExecutor::new(scheduler),
133 dispatcher,
134 }
135 }
136
137 /// Close this executor. Tasks will not run after this is called.
138 pub fn close(&self) {
139 self.inner.close();
140 }
141
142 /// Enqueues the given future to be run to completion on a background thread.
143 #[track_caller]
144 pub fn spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
145 where
146 R: Send + 'static,
147 {
148 self.spawn_with_priority(Priority::default(), future.boxed())
149 }
150
151 /// Enqueues the given future to be run to completion on a background thread with the given priority.
152 ///
153 /// When `Priority::RealtimeAudio` is used, the task runs on a dedicated thread with
154 /// realtime scheduling priority, suitable for audio processing.
155 #[track_caller]
156 pub fn spawn_with_priority<R>(
157 &self,
158 priority: Priority,
159 future: impl Future<Output = R> + Send + 'static,
160 ) -> Task<R>
161 where
162 R: Send + 'static,
163 {
164 if priority == Priority::RealtimeAudio {
165 Task::from_scheduler(self.inner.spawn_realtime(future))
166 } else {
167 Task::from_scheduler(self.inner.spawn_with_priority(priority, future))
168 }
169 }
170
171 /// Enqueues the given future to be run to completion on a background thread and blocking the current task on it.
172 ///
173 /// This allows to spawn background work that borrows from its scope. Note that the supplied future will run to
174 /// completion before the current task is resumed, even if the current task is slated for cancellation.
175 pub async fn await_on_background<R>(&self, future: impl Future<Output = R> + Send) -> R
176 where
177 R: Send,
178 {
179 use crate::RunnableMeta;
180 use parking_lot::{Condvar, Mutex};
181 use std::sync::{Arc, atomic::AtomicBool};
182
183 struct NotifyOnDrop<'a>(&'a (Condvar, Mutex<bool>));
184
185 impl Drop for NotifyOnDrop<'_> {
186 fn drop(&mut self) {
187 *self.0.1.lock() = true;
188 self.0.0.notify_all();
189 }
190 }
191
192 struct WaitOnDrop<'a>(&'a (Condvar, Mutex<bool>));
193
194 impl Drop for WaitOnDrop<'_> {
195 fn drop(&mut self) {
196 let mut done = self.0.1.lock();
197 if !*done {
198 self.0.0.wait(&mut done);
199 }
200 }
201 }
202
203 let dispatcher = self.dispatcher.clone();
204 let location = core::panic::Location::caller();
205 let closed = Arc::new(AtomicBool::new(false));
206
207 let pair = &(Condvar::new(), Mutex::new(false));
208 let _wait_guard = WaitOnDrop(pair);
209
210 let (runnable, task) = unsafe {
211 async_task::Builder::new()
212 .metadata(RunnableMeta { location, closed })
213 .spawn_unchecked(
214 move |_| async {
215 let _notify_guard = NotifyOnDrop(pair);
216 future.await
217 },
218 move |runnable| {
219 dispatcher.dispatch(runnable, Priority::default());
220 },
221 )
222 };
223 runnable.schedule();
224 task.await
225 }
226
227 /// Scoped lets you start a number of tasks and waits
228 /// for all of them to complete before returning.
229 pub async fn scoped<'scope, F>(&self, scheduler: F)
230 where
231 F: FnOnce(&mut Scope<'scope>),
232 {
233 let mut scope = Scope::new(self.clone(), Priority::default());
234 (scheduler)(&mut scope);
235 let spawned = mem::take(&mut scope.futures)
236 .into_iter()
237 .map(|f| self.spawn_with_priority(scope.priority, f))
238 .collect::<Vec<_>>();
239 for task in spawned {
240 task.await;
241 }
242 }
243
244 /// Scoped lets you start a number of tasks and waits
245 /// for all of them to complete before returning.
246 pub async fn scoped_priority<'scope, F>(&self, priority: Priority, scheduler: F)
247 where
248 F: FnOnce(&mut Scope<'scope>),
249 {
250 let mut scope = Scope::new(self.clone(), priority);
251 (scheduler)(&mut scope);
252 let spawned = mem::take(&mut scope.futures)
253 .into_iter()
254 .map(|f| self.spawn_with_priority(scope.priority, f))
255 .collect::<Vec<_>>();
256 for task in spawned {
257 task.await;
258 }
259 }
260
261 /// Get the current time.
262 ///
263 /// Calling this instead of `std::time::Instant::now` allows the use
264 /// of fake timers in tests.
265 pub fn now(&self) -> Instant {
266 self.inner.scheduler().clock().now()
267 }
268
269 /// Returns a task that will complete after the given duration.
270 /// Depending on other concurrent tasks the elapsed duration may be longer
271 /// than requested.
272 #[track_caller]
273 pub fn timer(&self, duration: Duration) -> Task<()> {
274 if duration.is_zero() {
275 return Task::ready(());
276 }
277 self.spawn(self.inner.scheduler().timer(duration))
278 }
279
280 /// In tests, run an arbitrary number of tasks (determined by the SEED environment variable)
281 #[cfg(any(test, feature = "test-support"))]
282 pub fn simulate_random_delay(&self) -> impl Future<Output = ()> + use<> {
283 self.dispatcher.as_test().unwrap().simulate_random_delay()
284 }
285
286 /// In tests, move time forward. This does not run any tasks, but does make `timer`s ready.
287 #[cfg(any(test, feature = "test-support"))]
288 pub fn advance_clock(&self, duration: Duration) {
289 self.dispatcher.as_test().unwrap().advance_clock(duration)
290 }
291
292 /// In tests, run one task.
293 #[cfg(any(test, feature = "test-support"))]
294 pub fn tick(&self) -> bool {
295 self.dispatcher.as_test().unwrap().scheduler().tick()
296 }
297
298 /// In tests, run tasks until the scheduler would park.
299 ///
300 /// Under the scheduler-backed test dispatcher, `tick()` will not advance the clock, so a pending
301 /// timer can keep `has_pending_tasks()` true even after all currently-runnable tasks have been
302 /// drained. To preserve the historical semantics that tests relied on (drain all work that can
303 /// make progress), we advance the clock to the next timer when no runnable tasks remain.
304 #[cfg(any(test, feature = "test-support"))]
305 pub fn run_until_parked(&self) {
306 let scheduler = self.dispatcher.as_test().unwrap().scheduler();
307 scheduler.run();
308 }
309
310 /// In tests, prevents `run_until_parked` from panicking if there are outstanding tasks.
311 #[cfg(any(test, feature = "test-support"))]
312 pub fn allow_parking(&self) {
313 self.dispatcher
314 .as_test()
315 .unwrap()
316 .scheduler()
317 .allow_parking();
318
319 if std::env::var("GPUI_RUN_UNTIL_PARKED_LOG").ok().as_deref() == Some("1") {
320 log::warn!("[gpui::executor] allow_parking: enabled");
321 }
322 }
323
324 /// Sets the range of ticks to run before timing out in block_on.
325 #[cfg(any(test, feature = "test-support"))]
326 pub fn set_block_on_ticks(&self, range: std::ops::RangeInclusive<usize>) {
327 self.dispatcher
328 .as_test()
329 .unwrap()
330 .scheduler()
331 .set_timeout_ticks(range);
332 }
333
334 /// Undoes the effect of [`Self::allow_parking`].
335 #[cfg(any(test, feature = "test-support"))]
336 pub fn forbid_parking(&self) {
337 self.dispatcher
338 .as_test()
339 .unwrap()
340 .scheduler()
341 .forbid_parking();
342 }
343
344 /// In tests, returns the rng used by the dispatcher.
345 #[cfg(any(test, feature = "test-support"))]
346 pub fn rng(&self) -> scheduler::SharedRng {
347 self.dispatcher.as_test().unwrap().scheduler().rng()
348 }
349
350 /// How many CPUs are available to the dispatcher.
351 pub fn num_cpus(&self) -> usize {
352 #[cfg(any(test, feature = "test-support"))]
353 if let Some(test) = self.dispatcher.as_test() {
354 return test.num_cpus_override().unwrap_or(4);
355 }
356 num_cpus::get()
357 }
358
359 /// Override the number of CPUs reported by this executor in tests.
360 /// Panics if not called on a test executor.
361 #[cfg(any(test, feature = "test-support"))]
362 pub fn set_num_cpus(&self, count: usize) {
363 self.dispatcher
364 .as_test()
365 .expect("set_num_cpus can only be called on a test executor")
366 .set_num_cpus(count);
367 }
368
369 /// Whether we're on the main thread.
370 pub fn is_main_thread(&self) -> bool {
371 self.dispatcher.is_main_thread()
372 }
373
374 #[doc(hidden)]
375 pub fn dispatcher(&self) -> &Arc<dyn PlatformDispatcher> {
376 &self.dispatcher
377 }
378}
379
380impl ForegroundExecutor {
381 /// Creates a new ForegroundExecutor from the given PlatformDispatcher.
382 pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
383 #[cfg(any(test, feature = "test-support"))]
384 let (scheduler, session_id): (Arc<dyn Scheduler>, _) =
385 if let Some(test_dispatcher) = dispatcher.as_test() {
386 (
387 test_dispatcher.scheduler().clone(),
388 test_dispatcher.session_id(),
389 )
390 } else {
391 let platform_scheduler = Arc::new(PlatformScheduler::new(dispatcher.clone()));
392 let session_id = platform_scheduler.allocate_session_id();
393 (platform_scheduler, session_id)
394 };
395
396 #[cfg(not(any(test, feature = "test-support")))]
397 let (scheduler, session_id): (Arc<dyn Scheduler>, _) = {
398 let platform_scheduler = Arc::new(PlatformScheduler::new(dispatcher.clone()));
399 let session_id = platform_scheduler.allocate_session_id();
400 (platform_scheduler, session_id)
401 };
402
403 let inner = scheduler::ForegroundExecutor::new(session_id, scheduler);
404
405 Self {
406 inner,
407 dispatcher,
408 not_send: PhantomData,
409 }
410 }
411
412 /// Close this executor. Tasks will not run after this is called.
413 pub fn close(&self) {
414 self.inner.close();
415 }
416
417 /// Enqueues the given Task to run on the main thread.
418 #[track_caller]
419 pub fn spawn<R>(&self, future: impl Future<Output = R> + 'static) -> Task<R>
420 where
421 R: 'static,
422 {
423 Task::from_scheduler(self.inner.spawn(future.boxed_local()))
424 }
425
426 /// Enqueues the given Task to run on the main thread with the given priority.
427 #[track_caller]
428 pub fn spawn_with_priority<R>(
429 &self,
430 _priority: Priority,
431 future: impl Future<Output = R> + 'static,
432 ) -> Task<R>
433 where
434 R: 'static,
435 {
436 // Priority is ignored for foreground tasks - they run in order on the main thread
437 Task::from_scheduler(self.inner.spawn(future))
438 }
439
440 /// Used by the test harness to run an async test in a synchronous fashion.
441 #[cfg(any(test, feature = "test-support"))]
442 #[track_caller]
443 pub fn block_test<R>(&self, future: impl Future<Output = R>) -> R {
444 use std::cell::Cell;
445
446 let scheduler = self.inner.scheduler();
447
448 let output = Cell::new(None);
449 let future = async {
450 output.set(Some(future.await));
451 };
452 let mut future = std::pin::pin!(future);
453
454 // In async GPUI tests, we must allow foreground tasks scheduled by the test itself
455 // (which are associated with the test session) to make progress while we block.
456 // Otherwise, awaiting futures that depend on same-session foreground work can deadlock.
457 scheduler.block(None, future.as_mut(), None);
458
459 output.take().expect("block_test future did not complete")
460 }
461
462 /// Block the current thread until the given future resolves.
463 /// Consider using `block_with_timeout` instead.
464 pub fn block_on<R>(&self, future: impl Future<Output = R>) -> R {
465 self.inner.block_on(future)
466 }
467
468 /// Block the current thread until the given future resolves or the timeout elapses.
469 pub fn block_with_timeout<R, Fut: Future<Output = R>>(
470 &self,
471 duration: Duration,
472 future: Fut,
473 ) -> Result<R, impl Future<Output = R> + use<R, Fut>> {
474 self.inner.block_with_timeout(duration, future)
475 }
476
477 #[doc(hidden)]
478 pub fn dispatcher(&self) -> &Arc<dyn PlatformDispatcher> {
479 &self.dispatcher
480 }
481
482 #[doc(hidden)]
483 pub fn scheduler_executor(&self) -> SchedulerForegroundExecutor {
484 self.inner.clone()
485 }
486}
487
488/// Scope manages a set of tasks that are enqueued and waited on together. See [`BackgroundExecutor::scoped`].
489pub struct Scope<'a> {
490 executor: BackgroundExecutor,
491 priority: Priority,
492 futures: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
493 tx: Option<mpsc::Sender<()>>,
494 rx: mpsc::Receiver<()>,
495 lifetime: PhantomData<&'a ()>,
496}
497
498impl<'a> Scope<'a> {
499 fn new(executor: BackgroundExecutor, priority: Priority) -> Self {
500 let (tx, rx) = mpsc::channel(1);
501 Self {
502 executor,
503 priority,
504 tx: Some(tx),
505 rx,
506 futures: Default::default(),
507 lifetime: PhantomData,
508 }
509 }
510
511 /// How many CPUs are available to the dispatcher.
512 pub fn num_cpus(&self) -> usize {
513 self.executor.num_cpus()
514 }
515
516 /// Spawn a future into this scope.
517 #[track_caller]
518 pub fn spawn<F>(&mut self, f: F)
519 where
520 F: Future<Output = ()> + Send + 'a,
521 {
522 let tx = self.tx.clone().unwrap();
523
524 // SAFETY: The 'a lifetime is guaranteed to outlive any of these futures because
525 // dropping this `Scope` blocks until all of the futures have resolved.
526 let f = unsafe {
527 mem::transmute::<
528 Pin<Box<dyn Future<Output = ()> + Send + 'a>>,
529 Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
530 >(Box::pin(async move {
531 f.await;
532 drop(tx);
533 }))
534 };
535 self.futures.push(f);
536 }
537}
538
539impl Drop for Scope<'_> {
540 fn drop(&mut self) {
541 self.tx.take().unwrap();
542
543 // Wait until the channel is closed, which means that all of the spawned
544 // futures have resolved.
545 let future = async {
546 self.rx.next().await;
547 };
548 let mut future = std::pin::pin!(future);
549 self.executor
550 .inner
551 .scheduler()
552 .block(None, future.as_mut(), None);
553 }
554}
555
556#[cfg(test)]
557mod test {
558 use super::*;
559 use crate::{App, TestDispatcher, TestPlatform};
560 use std::cell::RefCell;
561
562 /// Helper to create test infrastructure.
563 /// Returns (dispatcher, background_executor, app).
564 fn create_test_app() -> (TestDispatcher, BackgroundExecutor, Rc<crate::AppCell>) {
565 let dispatcher = TestDispatcher::new(0);
566 let arc_dispatcher = Arc::new(dispatcher.clone());
567 let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
568 let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
569
570 let platform = TestPlatform::new(background_executor.clone(), foreground_executor);
571 let asset_source = Arc::new(());
572 let http_client = http_client::FakeHttpClient::with_404_response();
573
574 let app = App::new_app(platform, asset_source, http_client);
575 (dispatcher, background_executor, app)
576 }
577
578 #[test]
579 fn sanity_test_tasks_run() {
580 let (dispatcher, _background_executor, app) = create_test_app();
581 let foreground_executor = app.borrow().foreground_executor.clone();
582
583 let task_ran = Rc::new(RefCell::new(false));
584
585 foreground_executor
586 .spawn({
587 let task_ran = Rc::clone(&task_ran);
588 async move {
589 *task_ran.borrow_mut() = true;
590 }
591 })
592 .detach();
593
594 // Run dispatcher while app is still alive
595 dispatcher.run_until_parked();
596
597 // Task should have run
598 assert!(
599 *task_ran.borrow(),
600 "Task should run normally when app is alive"
601 );
602 }
603
604 #[test]
605 fn test_task_cancelled_when_app_dropped() {
606 let (dispatcher, _background_executor, app) = create_test_app();
607 let foreground_executor = app.borrow().foreground_executor.clone();
608 let app_weak = Rc::downgrade(&app);
609
610 let task_ran = Rc::new(RefCell::new(false));
611 let task_ran_clone = Rc::clone(&task_ran);
612
613 foreground_executor
614 .spawn(async move {
615 *task_ran_clone.borrow_mut() = true;
616 })
617 .detach();
618
619 drop(app);
620
621 assert!(app_weak.upgrade().is_none(), "App should have been dropped");
622
623 dispatcher.run_until_parked();
624
625 // The task should have been cancelled, not run
626 assert!(
627 !*task_ran.borrow(),
628 "Task should have been cancelled when app was dropped, but it ran!"
629 );
630 }
631
632 #[test]
633 fn test_nested_tasks_both_cancel() {
634 let (dispatcher, _background_executor, app) = create_test_app();
635 let foreground_executor = app.borrow().foreground_executor.clone();
636 let app_weak = Rc::downgrade(&app);
637
638 let outer_completed = Rc::new(RefCell::new(false));
639 let inner_completed = Rc::new(RefCell::new(false));
640 let reached_await = Rc::new(RefCell::new(false));
641
642 let outer_flag = Rc::clone(&outer_completed);
643 let inner_flag = Rc::clone(&inner_completed);
644 let await_flag = Rc::clone(&reached_await);
645
646 // Channel to block the inner task until we're ready
647 let (tx, rx) = futures::channel::oneshot::channel::<()>();
648
649 let inner_executor = foreground_executor.clone();
650
651 foreground_executor
652 .spawn(async move {
653 let inner_task = inner_executor.spawn({
654 let inner_flag = Rc::clone(&inner_flag);
655 async move {
656 rx.await.ok();
657 *inner_flag.borrow_mut() = true;
658 }
659 });
660
661 *await_flag.borrow_mut() = true;
662
663 inner_task.await;
664
665 *outer_flag.borrow_mut() = true;
666 })
667 .detach();
668
669 // Run dispatcher until outer task reaches the await point
670 // The inner task will be blocked on the channel
671 dispatcher.run_until_parked();
672
673 // Verify we actually reached the await point before dropping the app
674 assert!(
675 *reached_await.borrow(),
676 "Outer task should have reached the await point"
677 );
678
679 // Neither task should have completed yet
680 assert!(
681 !*outer_completed.borrow(),
682 "Outer task should not have completed yet"
683 );
684 assert!(
685 !*inner_completed.borrow(),
686 "Inner task should not have completed yet"
687 );
688
689 // Drop the channel sender and app while outer is awaiting inner
690 drop(tx);
691 drop(app);
692 assert!(app_weak.upgrade().is_none(), "App should have been dropped");
693
694 // Run dispatcher - both tasks should be cancelled
695 dispatcher.run_until_parked();
696
697 // Neither task should have completed (both were cancelled)
698 assert!(
699 !*outer_completed.borrow(),
700 "Outer task should have been cancelled, not completed"
701 );
702 assert!(
703 !*inner_completed.borrow(),
704 "Inner task should have been cancelled, not completed"
705 );
706 }
707
708 #[test]
709 #[should_panic]
710 fn test_polling_cancelled_task_panics() {
711 let (dispatcher, _background_executor, app) = create_test_app();
712 let foreground_executor = app.borrow().foreground_executor.clone();
713 let app_weak = Rc::downgrade(&app);
714
715 let task = foreground_executor.spawn(async move { 42 });
716
717 drop(app);
718
719 assert!(app_weak.upgrade().is_none(), "App should have been dropped");
720
721 dispatcher.run_until_parked();
722
723 foreground_executor.block_on(task);
724 }
725
726 #[test]
727 fn test_polling_cancelled_task_returns_none_with_fallible() {
728 let (dispatcher, _background_executor, app) = create_test_app();
729 let foreground_executor = app.borrow().foreground_executor.clone();
730 let app_weak = Rc::downgrade(&app);
731
732 let task = foreground_executor.spawn(async move { 42 }).fallible();
733
734 drop(app);
735
736 assert!(app_weak.upgrade().is_none(), "App should have been dropped");
737
738 dispatcher.run_until_parked();
739
740 let result = foreground_executor.block_on(task);
741 assert_eq!(result, None, "Cancelled task should return None");
742 }
743}