简体   繁体   中英

How can I know when my code completes all the async work in zone, in Dart?

Consider I have code like this:

import 'dart:async';

foo() {
  print('foo');
}

bar() {
  print('bar');
}

void main() {
  runZoned(() {
    new Timer(const Duration(seconds: 1), foo);
    new Timer(const Duration(seconds: 2), bar);
  });
}

How can I know when all the async work inside a Zone is completed? That is, is it possible to know when all the async methods (either via timer, future, etc) that were registered within a zone are complete?

Initially zones did have an "onDone" callback. (See a usage in an old test here ). However we discovered that it is too hard to keep track of outstanding callbacks. For example: future.then(callback) registers a callback, but there is absolutely no guarantee that this callback will ever be invoked.

In fact, it is quite common that futures are never completed. Zones, themselves, contribute to this: when an error originates in a zone that has an error-handler the error will never leave the zone. That means that future-chains outside the zone won't be completed (neither with a value nor the error that got intercepted by the zone).

TL;DR: we had onDone on zones but removed it because it was impractical.

I tried to find this out too.
It seems the async queue is not implemented in Dart but managed by the VM.
The isolate running the Dart code gets a message to run the registered callbacks.

It might be possible to create a derived Zone that does some bookkeeping about scheduled tasks (add to its own queue before submitting the call to the default implementation and also wrapping the callback to get notified when the callback gets called, to remove it from the queue).

I hope someone comes up with a better answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM