加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 14:49:59 所属栏目:百科 来源:网络整理
导读:在Dart文档 The Event Loop and Dart (2013)中,它提到任何Future都被添加到Event队列中. 它还提到Microtask队列总是首先运行,然后是事件队列. 这个文档很旧,似乎是面向Web开发的,所以我不确定Flutter是否与我执行此代码时不同. FutureString myFunction() =
在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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读