在 Dart 中,当两个或多个任务等待同一个 Future 时,当 Future 完成时,任务是否按照执行等待的顺序获得通知/运行,即第一个执行等待的任务是第一个运行的。
这段代码保证输出2
int res = 0;
Future<void> foo1 () async
{
await Future.delayed(Duration(seconds: 2));
res = 2;
}
void main() async
{
await foo1();
print(res);
}
这段代码怎么样,稍微不太明显
int res = 0;
Future<void> foo1 () async
{
await Future.delayed(Duration(seconds: 2));
}
Future<void> foo2 (Future<void> f1) async
{
await f1;
res = 2;
}
Future<void> foo3 (Future<void> f1) async
{
await f1;
res = 3;
}
void main() async
{
res = 0;
Future<void> f1 = foo1();
foo3(f1);
foo2(f1);
await f1;
print(res);
}
有没有保证回调按照添加的顺序被调用。
The dart:async
库代码tries按该顺序调用回调,但这只是尽力而为。在某些情况下,通常会在 future 完成之前添加一个回调,而在 future 完成之后添加另一个回调,此时可能会以不同的顺序调用,因为它们是由不同的代码路径处理的。
触发这些情况并不容易,时机必须恰到好处,但这是可能的。
在此示例中,有 3 个等待f1
未来。它是最有可能的打印的值将是2
(因为没有什么奇特的事情发生),但是两者3
and 0
是允许的结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)