Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 61 ยท Asynchronous Dart

The Event Loop, Microtasks and Zones

See how Dart runs async code on one thread: the event queue, the microtask queue, the order of futures and timers, why blocking code freezes everything, and what zones do.

Futures and streams can look like magic: how can a program wait for a timer and a download "at the same time" when Dart code runs on a single thread? The answer is the event loop. Once you know how it works, the order in which asynchronous code runs stops being surprising, and you can predict the output of puzzles that trip up many developers.

The Dart code in this lesson is read-only. The TypeScript stand-ins include a small hand-written event loop, so you can step through the same rules and see the same ordering.

One thread, two queues

Each Dart isolate (see the Isolates lesson later in this chapter) runs your code on one thread and owns two queues:

  1. The microtask queue: tiny jobs that must run "right after the current code, before anything else".
  2. The event queue: everything coming from the outside world or from timers: I/O results, mouse clicks, Timer callbacks, messages from other isolates.

The loop is simple. After main() has run to the end, Dart repeats this forever:

  1. Run all microtasks until the microtask queue is empty (a microtask may add more microtasks; they run too).
  2. Take one event from the event queue and run its handler.
  3. Go back to step 1.

When both queues are empty and nothing is pending, the program ends.

flowchart TD
    A["main() finishes"] --> B{"microtask queue<br/>empty?"}
    B -- "no" --> C["run next microtask"]
    C --> B
    B -- "yes" --> D{"event queue<br/>empty?"}
    D -- "no" --> E["run one event handler"]
    E --> B
    D -- "yes" --> F["nothing left: program exits"]

The loop drains every microtask first, then handles exactly one event, then drains microtasks again.

Only one piece of Dart code runs at any moment. Nothing interrupts a function in the middle, so you do not need locks around ordinary variables. The price is that a long-running function holds up everyone else.

What goes into which queue?

You write Where the callback goes
scheduleMicrotask(fn) microtask queue
Future.microtask(fn) microtask queue
then callback on an already completed future microtask queue
code after an await of a completed future microtask queue
Future(fn) event queue (like a zero-length timer)
Future.delayed(d, fn) and Timer(d, fn) event queue, when the timer fires
I/O results, UI events, port messages event queue

Here is the classic ordering puzzle:

DART
import 'dart:async';

void main() {
  print('1 main start');

  Future(() => print('5 event: Future(...)'));
  Future.delayed(Duration.zero, () => print('6 event: delayed zero'));

  scheduleMicrotask(() => print('3 microtask A'));
  Future.microtask(() => print('4 microtask B'));

  print('2 main end');
}

The numbers show the order. main runs completely first (1, 2). Then the loop drains the microtasks in the order they were added (3, 4). Only then does it take events from the event queue, one at a time, in the order they were queued (5, 6).

then callbacks and the loop

A callback attached to a future runs as a microtask right after that future completes. That is why this prints A, B, C:

DART
void main() {
  Future(() => print('A')).then((_) => print('B'));
  Future(() => print('C'));
}

The first Future(...) is an event. When its handler finishes, the future completes and its then callback B becomes a microtask. The loop drains microtasks before taking the next event, so B goes before the second future's event C.

await and the order of async functions

await splits a function into pieces. The part before the first await runs at once. The rest runs later, from a microtask if the awaited future was already complete, or from an event if it had to wait:

DART
Future<void> main() async {
  print('1');
  await step();
  print('4');
}

Future<void> step() async {
  print('2');
}

Here step() prints 2 immediately, but main still has to wait one microtask turn before it continues with 4. The output is 1, 2, 4, but any other code that was already waiting in the microtask queue gets its turn before 4.

TypeScript A tiny event loop you can step through (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Blocking the loop

Because there is only one thread, code that does not return stops the whole loop. No timers fire, no events arrive, and a Flutter app cannot repaint:

DART
void main() {
  Future.delayed(const Duration(milliseconds: 10), () => print('timer fired'));

  var watch = Stopwatch()..start();
  while (watch.elapsedMilliseconds < 2000) {
    // busy waiting: the 10 ms timer is overdue, but nothing can run it
  }
  print('loop finished');       // printed first; the timer fires only afterwards
}

await does not help with this, because await hands control back to the loop, while a plain loop never does. The remedies are to break work into small pieces (await Future.delayed(Duration.zero) between chunks gives events a chance to run) or to move heavy computation to another isolate. Equally, keep microtasks short: a microtask that keeps scheduling new microtasks starves the event queue, so timers and I/O never get their turn.

TypeScript Microtasks run before timers (TypeScript stand-in with Node)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Zones

A zone is an execution context that the event loop carries along with callbacks. Every piece of code runs in some zone; the root zone is created for you, and Zone.current is the one you are in. Code you schedule (futures, timers, microtasks) keeps running in the zone where it was scheduled, so a zone can see and control everything that happens inside it, including asynchronous work that finishes much later.

Two features make zones useful:

  • Error handling for async code. runZonedGuarded runs a function and catches uncaught errors that escape from anything started inside it, even from futures nobody awaited:
DART
import 'dart:async';

void main() {
  runZonedGuarded(() {
    Future.delayed(const Duration(milliseconds: 10), () {
      throw StateError('nobody caught me');
    });
    print('started');
  }, (error, stack) {
    print('zone caught: $error');       // zone caught: Bad state: nobody caught me
  });
}
  • Overriding behaviour. A ZoneSpecification can change what print does or intercept scheduling, which is how some test tools capture output. Zone values (runZoned(..., zoneValues: {#user: 'ada'}) and Zone.current[#user]) pass context down to async callbacks without threading a parameter through every function.

Zones are an advanced tool. In everyday code you mostly meet them through runZonedGuarded as a last-chance error logger at the start of an app, and through frameworks that use them internally. Flutter provides its own error hooks for the same job, so check the framework's guidance before reaching for a zone.

Putting it together

When you read async code, ask three questions in order:

  1. Which parts run synchronously right now (everything up to the first await)?
  2. Which callbacks are microtasks (completed futures, then, await on completed futures)?
  3. Which are events (timers, Future(...), I/O)?

Run the synchronous part, then all microtasks in order, then events one by one, draining microtasks after each. This is enough to predict almost any output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After main() finishes, which jobs does the event loop run first?

    Microtasks always drain completely before the loop takes the next event.
  2. 2. What prints first? Future(() => print('X')); scheduleMicrotask(() => print('Y')); (both called from main)

    Future(...) is an event; scheduleMicrotask is a microtask. After main ends, Y runs first.
  3. 3. Why does a while loop that runs for two seconds freeze a Flutter app?

    Only one piece of code runs at a time. Until the loop ends, no events, timers or repaints are handled.
  4. 4. What is runZonedGuarded mainly used for?

    It runs code in a new zone with an error handler that receives errors nobody else caught, including those from unawaited futures.
  5. 5. A then callback is attached to a future that completes inside an event handler. When does the callback run?

    Completion callbacks are scheduled as microtasks, which are drained before the loop takes the next event.

Summary

  • Each isolate runs on one thread with a microtask queue and an event queue.
  • After main, the loop drains all microtasks, runs one event, and repeats.
  • scheduleMicrotask, then on completed futures and await continuations are microtasks; Future(...), timers, I/O and UI input are events.
  • Synchronous code runs to completion: a long loop blocks everything, and endless microtasks starve events.
  • Zones carry context along with async callbacks; runZonedGuarded is the standard last-chance error catcher.
  • To predict the order: synchronous code first, then microtasks, then events one at a time.

Next, run work on several threads with Isolates and Concurrency.