Dart:  Concurrency | main Isolates

Dart: Concurrency | main Isolates

ยท

2 min read

Table of contents

No heading

No headings in the article.

Introduction: Dart, a programming language known for its simplicity and versatility, offers a powerful feature called concurrency, allowing developers to perform multiple tasks simultaneously. In this blog post, we'll explore Dart's concurrency concept, focusing on main isolates. Fear not, as we'll keep things simple and provide examples to make it easy to understand.

Understanding Dart Concurrency: Concurrency in Dart refers to the ability of a program to execute multiple tasks concurrently, without waiting for each task to finish before starting the next one. Dart achieves this through isolates, which are independent units of execution. There are two main types of isolates: main isolates and spawned isolates.

Main Isolates Explained: A main isolate is the default execution thread of a Dart application. It's where your program starts running. While it's single-threaded (meaning it executes one task at a time), Dart's main isolates support asynchronous programming, allowing you to perform tasks without blocking the main thread.

Example: Asynchronous Programming in Main Isolates

void main() {
  print('Start of main function');

  // Asynchronous task using Future.delayed
  task1();

  // Asynchronous task using async/await
  task2();

  // Synchronous task
  print('End of main function');
}

void task1() {
  print('Task 1 started');

  // Simulating an asynchronous operation with Future.delayed
  Future.delayed(Duration(seconds: 2), () {
    print('Task 1 completed after 2 seconds');
  });

  print('Task 1 continues immediately');
}

void task2() async {
  print('Task 2 started');

  // Simulating an asynchronous operation with async/await
  await Future.delayed(Duration(seconds: 1));
  print('Task 2 completed after 1 second');
}

Explanation:

  • task1 demonstrates an asynchronous task using Future.delayed. It prints messages before and after the delay, showcasing non-blocking behavior.

  • task2 shows an asynchronous task using the async/await syntax. It pauses execution until the awaited asynchronous operation is complete.

Did you find this article valuable?

Support Vinit Mepani by becoming a sponsor. Any amount is appreciated!

ย