Dart Concurrency: Event Loop

Dart Concurrency: Event Loop

  • The event loop handles the execution of multiple chunks of your program over time.

  • The event loop is what allows multiple operations in a non-blocking way

  • The multi-threaded system kernel helps handle multiple operations executing in the background

  • If there is a piece of code that may delay the response, we can tell the event loop to keep it aside until the response is received.

  • When one of these operations completes, the kernel tells the event loop so that the appropriate callback may be queued to eventually be executed

Simply, An event loop’s job is to take an item from the event queue and handle it, repeating these two steps for as long as the queue has items.

Let’s know some points before to know how the Event loop works.

Event Handling Code

Dart uses asynchronous code to handle drawing events, mouse clicks, file I/O completions, timers, and so on. This code is called the Event Handling Code.

Dart’s Event Queues

A Dart app has two queues to run the Event Loop

  • \> Event Queue

The event queue contains all outside events: I/O, mouse events, drawing events, timers, messages between Dart isolates, and so on.

The event queue contains events both from Dart and from elsewhere in the system.

  • \> Microtask Queue

The microtask queue is necessary because the event-handling code sometimes needs to complete a task later, before returning control to the event loop.

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

Code Implementation

Let’s write a sample code to understand the event loop in a practical way

Sample Code:-

Output:-