从 Future.microtask
constructor 的文档中,它说:
* Creates a future containing the result of calling [computation]
* asynchronously with [scheduleMicrotask].
regular Future
constructor 的文档说明: * Creates a future containing the result of calling [computation]
* asynchronously with [Timer.run].
我想知道,它们对编码有什么样的影响,我们什么时候应该使用一种或另一种?
最佳答案
所有微任务都在任何其他 Future
s/Timer
s 之前执行。
这意味着当您想尽快异步完成一个小计算时,您将需要安排一个微任务。
void main() {
Future(() => print('future 1'));
Future(() => print('future 2'));
// Microtasks will be executed before futures.
Future.microtask(() => print('microtask 1'));
Future.microtask(() => print('microtask 2'));
}
你可以 run this example on DartPad 。事件循环将在其他 future 之前以先进先出的方式简单地选择所有微任务。当您安排微任务时会创建一个微任务队列,并且该队列在其他 future (事件队列)之前执行。
The Event Loop and Dart 有一篇过时的归档文章,其中涵盖了 事件队列 和 微任务队列 here 。
您还可以通过此 helpful resource 了解有关微任务的更多信息。
关于flutter - Flutter 中调用 Future 和 Future.microtask 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63070121/