[英]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. 最初,区域确实具有“ onDone”回调。 (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. 例如: future.then(callback)
注册了一个回调,但是绝对不能保证这个回调将被调用。
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. TL; DR:我们在区域上设置了onDone
,但由于不切实际而将其删除。
I tried to find this out too. 我也试图找出这一点。
It seems the async queue is not implemented in Dart but managed by the VM. 似乎异步队列不是在Dart中实现,而是由VM管理。
The isolate running the Dart code gets a message to run the registered callbacks. 运行Dart代码的隔离程序会收到一条消息,以运行已注册的回调。
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. 我希望有人能提出更好的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.