Sub topic 2
How the event loop orders your code
This chapter explains the order in which Dart runs your code. Once you know that order, you can predict the output of asynchronous programs and avoid ordering bugs.
What you should already know
You should be comfortable with Dart functions, variables, and types, and with generics such as List<int>. You should know how to run a file with dart run and how callbacks and anonymous functions work. You don't need to know how Future works internally. Later chapters cover it.
One thread, two queues
Each Dart isolate runs your code on a single thread. An isolate is Dart's unit of execution, with its own memory and its own event loop. Your main isolate has no second thread running Dart code at the same time, so two pieces of your code never run simultaneously.
The isolate keeps two queues of pending work:
- The microtask queue holds short tasks that must run right after the current code finishes, before anything else. Examples are the callbacks of an already-completed
Future. - The event queue holds everything that comes from outside the current code: timers, input and output results, mouse and touch events, and messages from other isolates.
The event loop is the runtime routine that takes tasks from these queues and runs each one to completion. A task that is running is never interrupted. The next task starts only when the current one returns.
The loop's algorithm
The loop follows a fixed order:
- Run
mainfrom start to end. This is ordinary synchronous code. - Run every task in the microtask queue until it is empty. Microtasks that queue more microtasks also run in this step.
- Take one task from the event queue and run it.
- Go back to step 2.
The program exits when both queues are empty and nothing is still waiting, such as an active timer or an open socket.
The key detail is the loop between B and C. The microtask queue is emptied completely before the loop looks at the event queue again.
A first ordering example
import 'dart:async';
void main() {
print('1 main start');
Future(() => print('4 event queue'));
scheduleMicrotask(() => print('3 microtask'));
print('2 main end');
}The output is numbered in the order it appears:
mainruns to the end, printing1 main startand2 main end. TheFuture(...)constructor andscheduleMicrotaskonly queue work. They don't run it.- The loop drains the microtask queue and prints
3 microtask. - The loop takes the event from the event queue and prints
4 event queue.
The microtask ran before the event even though the event was queued first. Queue position matters only within a single queue.
Which API uses which queue
| You write | Where the callback runs |
|---|---|
| `scheduleMicrotask(f)` | Microtask queue |
| `Future.microtask(f)` | Microtask queue |
| `Future(f)` | Event queue, through a zero-length timer |
| `Future.delayed(d, f)` | Event queue, after a timer of at least `d` |
| `Future.value(v).then(f)` | `f` runs as a microtask, because the Future is already complete |
| `future.then(f)` on a pending Future | `f` is queued as a microtask when the Future completes |
The last two rows matter most. Callbacks attached with then never run immediately, even on a completed Future. They always go through the microtask queue.
A longer ordering example
This program mixes both queues. Trace it yourself before reading the explanation.
import 'dart:async';
void main() {
print('1 main start');
Future(() => print('5 event A'));
Future.delayed(Duration.zero, () => print('6 event B'));
Future.microtask(() => print('3 microtask A'));
Future.value('x').then((_) => print('4 then on completed future'));
print('2 main end');
}The two print calls in main run first. Then the loop drains the microtasks in the order they were queued: the Future.microtask callback, then the then callback on the completed Future. Finally the two timer events run in creation order. Two timers with the same delay run in the order you created them.
Where `await` fits
An async function runs synchronously, like any function, until it reaches its first await. At that point it pauses and returns a Future to its caller. The rest of the function becomes a callback that runs after the awaited Future completes.
Future<void> task() async {
print('2 task start (still synchronous)');
await null;
print('4 task resumed (microtask)');
}
void main() {
print('1 before');
task();
print('3 after call');
}The output is 1, 2, 3, 4. The call task() prints line 2 before it returns, so line 2 appears before 3 after call. The await null pauses the function even though null is not a Future. Dart wraps the value, and the function resumes in a microtask after main finishes.
Many ordering bugs come from forgetting this. Code before the first await runs in the caller's turn, and code after it runs later.
Microtasks can starve events
The loop empties the microtask queue before it takes any event. If microtasks keep adding more microtasks, no event ever runs.
import 'dart:async';
void main() {
Future(() => print('event'));
void step(int n) {
if (n > 3) return;
print('microtask $n');
scheduleMicrotask(() => step(n + 1));
}
scheduleMicrotask(() => step(1));
}The output is microtask 1, microtask 2, microtask 3, and then event. The chain stops at 3 here. If it never stopped, event would never print. Timers, input, and in Flutter even screen redraws would freeze.
Blocking the loop delays everything
The loop runs one task at a time and never interrupts it. A slow synchronous task therefore delays every task behind it, including timers.
void main() {
final sw = Stopwatch()..start();
Future.delayed(const Duration(milliseconds: 100), () {
print('timer fired after ${sw.elapsedMilliseconds} ms');
});
while (sw.elapsedMilliseconds < 500) {}
print('busy loop done');
}The program prints busy loop done first. The timer was due at 100 ms, but its callback cannot start until main returns. It reports about 500 ms.
This shows two facts:
- The duration in
Future.delayedis a minimum wait, not an exact time. - An
asyncfunction does not run in the background. If the work between twoawaits is CPU-heavy, the whole isolate stalls. In a Flutter app, the UI freezes. The last chapters of this tutorial coverIsolate.run, which moves such work to another isolate.
Common mistakes
- Expecting
thencallbacks to run immediately. Even on an already-completed Future, the callback is delayed until the current synchronous code finishes. - Assuming a short
Future.delayedruns before a microtask. Microtasks always run first. A delay of zero still goes through the event queue. - Relying on exact timing between unrelated timers. Order is guaranteed only for timers with equal or increasing deadlines. Don't depend on microsecond-level differences.
- Treating
asyncas multithreading. It lets one thread switch between tasks atawaitpoints. It adds no parallel computation.
Exercises
Exercise
What does this program print, and in what order? import 'dart:async'; void main() { print('A'); Future(() => print('B')); Future.microtask(() => print('C')); print('D'); }
Show answer
A, D, C, B. The synchronous prints A and D run first while main executes. The loop then drains the microtask queue, printing C. Only after that does it take the event queued by Future(...), printing B.
Exercise
A program calls Future.delayed(const Duration(milliseconds: 50), ...) and then runs a synchronous loop that takes 300 ms. When does the delayed callback run, and why?
Show answer
It runs after about 300 ms, once main finishes. The event loop runs one task at a time and never interrupts it. The timer's callback is in the event queue and must wait until the current synchronous task returns. The 50 ms is only the minimum delay.