微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

dart – 事件队列和微任务队列

在Dart文档 The Event Loop and Dart (2013)中,它提到任何Future都被添加到Event队列中.

它还提到Microtask队列总是首先运行,然后是事件队列.

这个文档很旧,似乎是面向Web开发的,所以我不确定Flutter是否与我执行此代码时不同.

Future<String> myFunction() => new Future.value('Hello');
Future<String> myFunction2() => new Future.value('Hello2');
Future<void> maintest() async {
  debugPrint("Sync1");  
  myFunction().then(debugPrint);
  scheduleMicrotask(() { debugPrint("Microtask"); });
  myFunction2().then(debugPrint);  
  debugPrint("Sync2");
}

我得到了一个输出

I/Flutter ( 6731): Sync1
I/Flutter ( 6731): Sync2
I/Flutter ( 6731): Hello
I/Flutter ( 6731): Microtask
I/Flutter ( 6731): Hello2

但是如果所有Microtasks都要在下一个Event循环之前运行,那不应该这样吗?

I/Flutter ( 6731): Sync1
I/Flutter ( 6731): Sync2
I/Flutter ( 6731): Microtask // This running first before the Futures?
I/Flutter ( 6731): Hello
I/Flutter ( 6731): Hello2

解决方法

如果你在没有调用.then的情况下调用方法就是这种情况

A way to add a task to the microtask queue is to invoke then() on a
Future that’s already complete.

所以当你调用myFunction().然后(打印);将未来添加到微任务队列中.

在没有’.then’的情况下拨打电话时的一些奖励事实:
根据docs,有2个错误.这些错误是固定的,但问题仍然存在:(

The upshot of these bugs: The first task that you schedule with
scheduleMicrotask() seems like it’s on the event queue.

A workaround is to put your first call to scheduleMicrotask() before your first call to new Future()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐