Dart - Event Loop, Microtask & Event Queue

Understanding code execution in Dart is very important if you want to build application with Dart language. This article explains code execution in Dart, including what is event loop in Dart, how it works, and how tasks are stored in queues.

Dart Uses Single Thread Execution

Dart is a single threaded languages. Dart can only execute an operation at a time. It cannot be interrupted until the operation has been finished.

For example, there is a synchronous function like below.

  void myLoop(){
      for (int i = 0; i < 1000000; i++) {
          print('Current number is $i');
      }
  }

Once it's started to be executed, no other thing can be executed until it finishes. That means if the function takes some time to execute, the application will be blocked.

Event Loop

To manage code execution, Dart uses something called Event Loop.

When you start a Dart application, first it initializes two queues: Microtask Queue and Event Queue. Then, it executes the main() method and after main() exits, it creates an Event Loop. The Event Loop is responsible for controlling code execution by reading the queues.

Flutter - Event Loop Lifecycle

As you can see on the figure, on every Event Loop, first it fetches all microtasks from Microtask Queue. All Microtasks will be executed and dequeued. After the Microtask queue is empty, it executes only the first item in Event Queue. Both Microtask Queue and Event Queue use FIFO (First In First Out) order.

Microtask Queue

The MicroTask Queue is used to store some very short asynchronous internal actions. All of the actions in Microtask Queue will  be executed before the Event Queue turn

Microtask is usually created if we need to complete a task later, but before returning control to the event loop. For example, mutation changes of observable object are grouped and reported asynchronously.

To add an item to Microtask Queue, use scheduleMicrotask function.

Event Queue 

External actions like I/O, mouse, gesture, drawing, timers, and messages between Dart isolates are stored on Event Queue. As it has been explained above, only one item in Event Queue can be executed on every event loop after there is no available microtask to run.

To add an item to the end of Event Queue, create a new Future.