0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【入門】async await

Posted at

Dartの非同期処理方法

Dartはシングルスレッド方式によりプロセス管理を行なっている。

イベントループとは

Dartの非同期処理の手法。発生したイベントをイベントキューにためて、溜まったイベントを順次処理することによりノンブロッキング処理を可能としている。
ex) Javascript, Dart

マルチスレッドとは

よく比較対象として議論されるのがマルチスレッド。 
マルチスレッドはカーネルが複数の命令を処理して、ある処理をバックグラウンドで同時に行う手法。
ex) Java, C++, Python

Dartの処理系(Event Queue, Microtask Queue)

Event Queue

メインとなるキュー。I/O、マウスイベント、描画イベント、メッセージ等DartやDart以外のシステムのイベントもイベントキューに格納される。

Microtask Queue

クロージャー等後から処理を行いたいものをキューに格納するためのもの。マイクロタスクキューに格納されているイベントはイベントキューの処理前に全て呼び出される。

※誤りがありましたら、ご指摘をお願いします🙇

async, awaitの正体

async : 非同期処理を行いますよと関数にラベルをつけるもの。
await : return値がFuture<T>async関数に対して、awaitキーワードを用いると T型のreturn値を取得することができる。
awaitキーワードをつけないとFuture instanseが戻ってくる

実際の処理

1. 同期処理

void process1() {
  print('Done Process1');
}

void process2() {
  print('Done Process2');
}

void process3() {
  print('Done Process3');
}

void main() {
    process1();
    process2();
    process3();
}

// 出力結果
// Done Process1
// Done Process2
// Done process3
  1. 非同期処理 その1(関数にasync/await)
void process1() {
  print('Done Process1');
}

Future<void> process2() async {
  Future<String> future = Future.delayed(Duration(seconds: 2), () =>'Done process2');
  future.then((value) => print(value));
}

void process3() {
  print('Done Process3');
}

void main() {
    process1();
    process2();
    process3();
}

// 出力結果
// Done Process1
// Done Process3
// Done process2

process2()が非同期処理の対象になる。


参考記事
https://medium.com/@kawanojieee/dart-async-await-394846fb3d2c
https://medium.flutterdevs.com/event-loop-in-dart-226a7487b4aa

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?