[英]Flutter/Dart: How to perform Synchronization
問題不言自明,這里我有一個列表,它調用了幾次write
方法,但它沒有按順序提供 output。
void main() {
List<int> list = [1, 2, 3, 4];
write(list);
write(list);
}
write
函數獲取列表並以 1 毫秒的延遲打印值
write(List<int> values) async {
for (int value in values) {
await Future.delayed(new Duration(microseconds: 1));
print(value);
}
}
Output:
I/flutter (21092): 1
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 3
I/flutter (21092): 4
I/flutter (21092): 4
預期 Output:
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
要實現這一點,請使用synchronized
庫
將此添加到您的包的 pubspec.yaml 文件中:
dependencies:
synchronized: ^2.2.0+2
代碼片段:
write(List<int> values) async {
var lock = Lock();
for (int value in values) {
lock.synchronized(() {
Future.delayed(new Duration(seconds: 2));
});
print(value);
}
}
Output:
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
注意: synchronized
塊將首先運行所有列表,然后只允許進入第二個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.