Concurrency in Dart

- Synchronous tasks in the main isolate thread are always run immediately. You can’t interrupt them.
- If Dart finds any long-running tasks that agree to be postponed, Dart puts them in the event queue.
- When Dart finishes running the synchronous tasks, the event loop checks the microtask queue. If the microtask queue has any tasks, the event loop puts them on the main thread to execute next. The event loop keeps checking the microtask queue until it’s empty.
- If the synchronous tasks and microtask queue are both empty, the event loop sends the next waiting task in the event queue to run on the main thread. Once it gets there, the code executes synchronously. Like any other synchronous code, nothing can interrupt it after it starts.
- If new microtasks enter the microtask queue, the event loop handles them before the next event in the event queue.
- This process continues until all the queues are empty.
Order of priority
- Synchronous code
- Microtask
- Event queue
Note you can make a new isolate. But they do not have shared memory or queues.
Add to Event queue
Future(
() => print('second'),
);Add to Microtask queue
Future.microtask(
() => print('third'),
);