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
*/
void main() {
print(Future((){print("a");}));// イベントキューの末尾に追加。
print("b"); // この処理はすでにイベントキューに入っているため、上記のコールバックよりも先に実行される。
// Instance of '_Future<Null>'
// b
// a
// ※ もし、他の処理でも非同期処理をしているのであれば、b と a の間に他の処理が入り込む可能性がある点に注意。
}
Future((){print("a");});
Future.microtask((){print("b");});
// b
// a
new Future.sync(() => 値)
と等価。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
import 'dart:async';
void main() async{
Future((){print(1);});
Future.microtask((){print(2);});
await test();
print(4);
}
Future<void> test() async => print(3);
// 3
// 2
// 4
// 1
void main() async {
print(await f1());
print(await f2());
}
Future<int> f1() async {
return Future(()=>1);
}
Future<int> f2() => Future.value(2);
// 1
// 2
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 Future.wait(
[
Future.delayed(const Duration(milliseconds: 100), () => print(1)),
Future.delayed(const Duration(milliseconds: 1), ()=> print(2)),
],
);
print(3);
// 2
// 1
// 3
factory Future(FutureOr<T> computation()) {
_Future<T> result = new _Future<T>();
Timer.run(() {
try {
result._complete(computation());
} catch (e, s) {
_completeWithErrorCallback(result, e, s);
}
});
return result;
}
Future.sync((){print("1");}).then((_){print("2");});
print("3");
// 1
// 3
// 2