关于 Dart 中未来执行顺序的问题
Question about Future execution order in Dart
这是我的代码,
Future<int> test() {
print('Start test()');
for (var i = 1; i < 100000; i++) {
for (var j = 1; j < 100000; j++) {
var k = i * j;
}
}
print('After a long running task in test()');
return Future<int>.value(1);
}
void main() {
test().then((result) => print('Done with test()'));
print('Done with main().');
}
这是输出,
Start test()
After a long running task in test()
Done with main().
Done with test()
我的问题是, 'Done with main()' 不应该在 'After a long running task in test()' 之前打印吗?
如果您想跳过任务,请使用Future.microtask()
。
示例:
Future<int> test() {
print('Start test()');
for (var i = 1; i < 100000; i++) {
for (var j = 1; j < 100000; j++) {
var k = i * j;
}
}
print('After a long running task in test()');
return Future<int>.value(1);
}
void main() {
Future.microtask(test);
print('Done with main().');
}
输出:
Done with main().
Start test()
After a long runnin task in test()
这是我的代码,
Future<int> test() {
print('Start test()');
for (var i = 1; i < 100000; i++) {
for (var j = 1; j < 100000; j++) {
var k = i * j;
}
}
print('After a long running task in test()');
return Future<int>.value(1);
}
void main() {
test().then((result) => print('Done with test()'));
print('Done with main().');
}
这是输出,
Start test()
After a long running task in test()
Done with main().
Done with test()
我的问题是, 'Done with main()' 不应该在 'After a long running task in test()' 之前打印吗?
如果您想跳过任务,请使用Future.microtask()
。
示例:
Future<int> test() {
print('Start test()');
for (var i = 1; i < 100000; i++) {
for (var j = 1; j < 100000; j++) {
var k = i * j;
}
}
print('After a long running task in test()');
return Future<int>.value(1);
}
void main() {
Future.microtask(test);
print('Done with main().');
}
输出:
Done with main().
Start test()
After a long runnin task in test()