我有以下 Dart 程序:
import 'package:pedantic/pedantic.dart';
Future someFunc() async {
for (var i = 0; i < 100; i++) {
print('Value of i in someFunc(): ' + i.toString());
}
}
Future someOtherFunc() async {
for (var i = 0; i < 100; i++) {
print('Value of i in someOtherFunc(): ' + i.toString());
}
}
Future<int> main() async {
unawaited(someFunc());
unawaited(someOtherFunc());
print('End of program...');
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我执行这个时,输出是:
Value of i in someFunc(): 0
Value of i in someFunc(): 1
Value of i in someFunc(): 2
...
Value of i in someFunc(): 99
Value of i in someOtherFunc(): 0
Value of i in someOtherFunc(): 1
Value of i in someOtherFunc(): 2
...
Value of i in someOtherFunc(): 99
End of program...
Run Code Online (Sandbox Code Playgroud)
看起来一切都是同步执行的。我期待类似的事情:
Value of i in someFunc(): 0
Value of i in someFunc(): 1
Value of i in someOtherFunc(): 0
Value of i in someFunc(): 3
End of program...
Value of i in someOtherFunc(): 1
(etc...)
Run Code Online (Sandbox Code Playgroud)
如何在 Dart 中创建异步“即发即忘”函数/方法?
您看到此代码同步执行的原因是因为 Dart 中的异步方法执行起来就好像它们是同步的,直到第一个await,此时该方法的执行将暂停,直到await完成。如果您在方法中执行实际的异步工作,您会看到如您所期望的交错执行。
例如,对您的代码进行一些细微的修改,大致会产生您期望的行为:
import 'package:pedantic/pedantic.dart';
Future someFunc() async {
for (var i = 0; i < 100; i++) {
// Future.microtask is used to schedule work on the microtask queue,
// which forces this method to suspend execution and continue on to someOtherFunc.
// If you were doing some actual asynchronous work, you wouldn't need this.
await Future.microtask(() => print('Value of i in someFunc(): ' + i.toString()));
}
}
Future someOtherFunc() async {
for (var i = 0; i < 100; i++) {
await Future.microtask(() => print('Value of i in someOtherFunc(): ' + i.toString()));
}
}
Future<int> main() async {
unawaited(someFunc());
unawaited(someOtherFunc());
print('End of program...');
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我强烈建议您阅读Dart 事件循环和微任务队列,这将使您更好地了解异步在 Dart 中的工作原理
| 归档时间: |
|
| 查看次数: |
1438 次 |
| 最近记录: |