docs

TOP(About this memo)) > 一覧(Dart) > 並行処理

ドキュメント

参考

並列処理とアイソレート

イベントキュー

マイクロタスクキュー

並行処理の順番を検証したサンプルコード

import 'dart:async';

void main() async{
  StreamController<void> sc = StreamController<void>();
  sc.add(null);
  sc.stream.listen((_) {
    print("1");
  });
  
  Future.delayed(const Duration(milliseconds:500), (){print("2");});
  Future((){print("3");});
  Future.microtask((){print("4");}).then((_){print("5");});
  print("6");
  Future.sync((){print("7");}).then((_){print("8");});
  test().then((_){print("9");});
  await Future.sync((){print("10");}).then((_){print("11");});
}

Future<void> test() async{
  print("12");
  Timer.run((){print("13");});
}

/*

6
7
12
10
1
4
5
8
9
11
3
13
2

*/

Futureオブジェクト

Future.microtask

Future((){print("a");});
Future.microtask((){print("b");});
// b
// a

Future.value(値)

then

Register callbacks to be called when this future completes. When this future completes with a value, the [onValue] callback will be called with that value. If this future is already completed, the callback will not be called immediately, but will be scheduled in a later microtask.

void main() {
 print(Future(() => 1).then((a) => a).then((a)=> print(a))); 
 print(2);
}
// Instance of '_Future<void>'
// 2
// 1

async/await

(参考)Futureではない値のFutureのawait

import 'dart:async';

void main() async{ 
  f1();
  f2();
  f3();
  f4();
  f5();
  print(0);
}

Future<void> f1() async => print(await f1c());
Future<int> f1c() async => Future(() => 1); // 最も遅い
Future<void> f2() async => print(await f2c());
Future<int> f2c() async => 2;
Future<void> f3() async => print(await 3);
Future<void> f4() async => print(await Future.value(4));
Future<void> f5() async => print(5);// 単なるasync関数は通常の処理と変わらない
// 5
// 0 
// 2
// 3
// 4
// 1

複数のawait

  await Future.wait(
    [
      Future.delayed(const Duration(milliseconds: 100), () => print(1)),
      Future.delayed(const Duration(milliseconds: 1), ()=> print(2)),
    ],
  );
  print(3);
  // 2
  // 1
  // 3

Timer.run

Future.sync

Future.sync((){print("1");}).then((_){print("2");});
print("3");
// 1
// 3
// 2

FakeAsync