Dart 是一个在单线程中运行的程序。在程序中执行一个需要长时间的执行的操作,为避免卡住UI主线程,我们会用到异步(future),可以使程序在等待一个耗时操作完成时继续处理其他工作。
在进入正题之前,我们先了解一下 Dart 的消息循环机制:
Future 是什么?这里我们用小篇幅简单描述一下。future是一个异步的执行操作,可以在不阻塞代码的情况下实现耗时功能。
main() { Future(() { print('我是一个耗时操作'); }).then((value){ print('future 结束了'); }); print('main'); }
//打印结果
main
我是一个耗时操作
future 结束了
在项目中,我们使用 Future
、Async
、await
相互组合实现异步编码。
上面的篇幅我们说过,future 创建后会被直接加入到事件队列依次执行。那么在上一个 future 在没有标识完成前,下一个 future 可以被执行吗?
小编写了几个样例来做实验:
main() { Test1.future1().then((value) => print(value)); Test1.future2().then((value) => print(value)); } abstract class Test1 { static Future<String> future1() async { return Future(() async { print('开始 future1'); await TestTool.timeConsume(1000000000); //耗时运算 print('一千年过去了'); return 'future1 结束了'; }); } static Future<String> future2() async { return Future(() async { print('开始 future2'); await TestTool.timeConsume(1000); //耗时运算 print('继续 future2'); return 'future2 结束了'; }); } }
//打印结果
开始 future1
一千年过去了
future1 结束了
开始 future2
继续 future2
future2 结束了
实验结果:
main() { Test2.future1().then((value) => print(value)); Test2.future2().then((value) => print(value)); } abstract class Test2 { static Future<String> future1() async { print('开始 future1'); await TestTool.timeConsume(1000000000);//耗时运算 print('一千年过去了'); return 'future1 结束了'; } static Future<String> future2() async { print('开始 future2'); await TestTool.timeConsume(1000);//耗时运算 print('继续 future2'); return 'future2 结束了'; } }
//打印结果
开始 future1
开始 future2
一千年过去了
future1 结束了
继续 future2
future2 结束了
实验结果:
main() { Test3.future1().then((value) => print(value)); Test3.future2().then((value) => print(value)); } abstract class Test3 { static Future<String> future1() async { print('开始 future1'); await Future(() => TestTool.timeConsume(1000000000));//耗时运算 print('一千年过去了'); return 'future1 结束了'; } static Future<String> future2() async { print('开始 future2'); await TestTool.timeConsume(1000);//耗时运算 print('继续 future2'); return 'future2 结束了'; } }
//打印结果
开始 future1
开始 future2
继续 future2
future2 结束了
一千年过去了
future1 结束了
实验结果:
附上耗时代码:
abstract class TestTool { ///耗时操作 static Future<int> timeConsume(int num) async { final result = _timeConsume(num); return result; } static int _timeConsume(int num) { int count = 0; while (num > 0) { if (num % 2 == 0) { count++; } num--; } return count; } }
综合上述三种写法分析:
future方法体内部不属于可靠的'原子性操作',不同的写法有不同的差异性。 如果想将整个方法体内部作为不可拆分的执行单位。在外层使用Future进行包裹处理,如写法一中Test1示例:
static Future<T> funcName() async { return Future(() async { ... 具体的方法体内容 ... return result; }); }
future在创建的同时,就会被加入到event事件队列中。事件队列是依次执行的,但每个future的完成顺序与加入的顺序不存在可靠的一致性。 如果在业务内想保持顺序的一致性,可参考上述写法,或使用 await
进行强制等待如:
main() async { await Test2.future1().then((value) => print(value)); Test2.future2().then((value) => print(value)); }
这样写,future2 就一定会在 future1 执行完成后才进入开始状态。