Dart isolates are a powerful feature for achieving concurrency in Dart applications. They provide a way to run code in parallel, improving performance and responsiveness.
Isolates are separate units of execution in Dart, similar to threads but with their own memory heap. They allow developers to perform computationally intensive tasks without blocking the main thread.
To create an isolate, use the Isolate.spawn()
method. Here's a simple example:
import 'dart:isolate';
void isolateFunction(SendPort sendPort) {
sendPort.send('Hello from isolate!');
}
void main() async {
final receivePort = ReceivePort();
await Isolate.spawn(isolateFunction, receivePort.sendPort);
final message = await receivePort.first;
print(message);
}
In this example, we create an isolate that sends a message back to the main isolate.
Isolates communicate through message passing. They use SendPort
and ReceivePort
for this purpose.
Here's a more practical example using isolates for number crunching:
import 'dart:isolate';
import 'dart:math';
void calculatePrimes(SendPort sendPort) {
final primes = [];
for (int i = 2; i < 10000; i++) {
if (isPrime(i)) primes.add(i);
}
sendPort.send(primes);
}
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
void main() async {
final receivePort = ReceivePort();
await Isolate.spawn(calculatePrimes, receivePort.sendPort);
final primes = await receivePort.first;
print('Found ${primes.length} prime numbers');
}
This example demonstrates how to use an isolate to perform a computationally intensive task (finding prime numbers) without blocking the main thread.
Dart isolates are a powerful tool for concurrent programming. They enable developers to write efficient, responsive applications by leveraging multi-core processors. When used appropriately, isolates can significantly enhance the performance of Dart applications.
For more advanced asynchronous programming techniques, explore Dart Async and Await and Dart Streams.