CodeBlanks Logo Icon CodeBlanks

Summary - Concurrency

Combine event loop, microtasks and Zone to write a scheduler.

Summary - Concurrency

This group covered Dart's concurrency model: a single-threaded event loop, two queues (event and microtask), the Future scheduler and Zones.

Core principle: microtasks run before events in each turn. Future.value and Future.microtask schedule as microtasks; Future.delayed schedules as an event.

A Zone is an execution-environment abstraction used for async error handling and task interception.

Practice Summary: microtask + event order

Make main async. Add print('başla');. Add await Future.microtask(() => print('micro'));. Add print('bitti');.

Starter code

main.dart
void main() {
  // make async; print 'başla'; microtask prints 'micro'; print 'bitti'
}

Sample solution

main.dart
void main() async {
  print('başla');
  await Future.microtask(() => print('micro'));
  print('bitti');
}

Expected output

başla
micro
bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which adds to the event queue?

  • Future.value
  • Future.microtask
  • scheduleMicrotask
  • Future.delayed Correct answer

Explanation: Future.delayed adds a task to the event queue.

2 Match the concepts

Term Meaning
Event loop Single thread
Microtask Priority queue
Future.delayed Event queue
Zone Execution environment

3 Schedule a microtask

Question
____(() => print('m'));
Answer
scheduleMicrotask(() => print('m'));

Explanation: scheduleMicrotask adds to the microtask queue.

All lessons in Advanced