Flutter learning - Dart threads and events

Dart is single-threaded, and all code runs in an isolate . The main function of the app entry is an isolate. When needed, you can use isolateAPI to create a new isolate, and different isolates can only communicate through isolateAPI.

The Dart operating environment is driven by events, and messages are obtained from the queue through the event loop. There are two queues in an isolate, event queue and microtask queue

7700793-9c05b03430ae4e7c.png

As shown in the figure: when the app starts running, the event loop processes the microtask queue first , and starts processing the event queue until the microtask queue is empty. If the event queue is not empty, execute one event at a time, and then re-judge whether the microtask is empty after execution.
Therefore, you can put the things to be done after processing the current event, before processing the next event, or before processing all events in the microtask queue. Note : drawing and interaction are placed in the event queue, so the tasks in the microtask queue should not be too time-consuming , otherwise it will cause lag.
When both queues are empty, the app exits normally.

The Future object mentioned earlier is an event, and creating a Future will add a record to the event queue. In async await , the event marked by await is an event.

Here's an example:
two Future objects output strings on the console:

onPressed: () async {
   new Future((){print('future1');});
   new Future((){print('future2');});
}),

The result after execution is shown in the figure
69D25DB3-008B-442A-B223-453C86730DE7.png

Here the two Futures are two events, and now adding two microtask events is also an output string.

onPressed: () async {
   new Future((){print('future1');});
   Future.microtask(() {
    print('microtask1');
   });
   new Future((){print('future2');});
   Future.microtask(() {
    print('microtask2');
   });
}),

The result after execution is shown in the figure
844F21BD-FB44-4068-B8DA-96ACFE939982.png

It can be seen that the event loop will process the microtask queue first every time, and then process the event queue when the microtask is empty.

Guess you like

Origin blog.csdn.net/github_33420275/article/details/88118808