Skip to content

Isolates(隔离区)——Dart 的并发模型

什么是 Isolate?

Isolate 是 Dart 实现真正并行的方式。每个 isolate 都有自己的内存和事件循环。

基本 Isolate

dart
import 'dart:isolate';

void heavyComputation(SendPort sendPort) {
  int sum = 0;
  for (int i = 0; i < 1000000000; i++) {
    sum += i;
  }
  sendPort.send(sum);
}

void main() async {
  ReceivePort receivePort = ReceivePort();
  
  await Isolate.spawn(heavyComputation, receivePort.sendPort);
  
  var result = await receivePort.first;
  print('结果:$result');
}

Compute 函数

dart
import 'package:flutter/foundation.dart';

int expensiveFunction(int value) {
  int result = 0;
  for (int i = 0; i < value; i++) {
    result += i;
  }
  return result;
}

void main() async {
  int result = await compute(expensiveFunction, 1000000);
  print('结果:$result');
}

使用场景

  • 重计算
  • 图像处理
  • 数据解析
  • 网络操作

下一步