通过Isolate
import 'dart:isolate';
void main(List<String> args) {
print('strat');
//开启一个并发线程
Isolate.spawn(cldc, 100);
print('end');
}
void cldc(int count) {
int tolte = 0;
for (int i = 0; i < count; i++) {
tolte = tolte + i;
}
print(tolte);
}
通过管道
import 'dart:isolate';
void main(List<String> args) async{
print('strat');
//1.创建管道
ReceivePort receivePort=ReceivePort();
//2.创建Isolate
Isolate isolate=await Isolate.spawn<SendPort>(cldc,receivePort.sendPort);
//3.监听管道
receivePort.listen((message) {
print(message);
receivePort.close();
isolate.kill();
},);
print('end');
}
void cldc(SendPort send) {
int tolte = 0;
for (int i = 0; i < 100; i++) {
tolte = tolte + i;
}
return send.send(tolte);
}
使用compute
compute 是一个方便的函数,用于在后台 Isolate 中执行计算密集型的任务,并返回结果给调用者。它简化了在 Isolate 之间传递消息和处理并发任务的过程。
compute 函数接受两个参数:一个是要在后台执行的函数,另一个是该函数的输入参数。它会自动创建和管理一个新的 Isolate,并将输入参数传递给该函数。当函数执行完毕后,结果会被返回给调用者。
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
main() {
print('main start');
runApp(MyApp());
int fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
void com() async {
int result = await compute(fibonacci, 10);
print('Fibonacci result: $result');
}
com();
print('main end');
}
我们定义了一个计算斐波那契数列的函数 fibonacci,然后使用 compute 函数以参数 10 调用它。compute 函数会在后台 Isolate 中执行 fibonacci 函数,并返回结果给调用者。最后,我们打印出计算的结果。
使用 compute 的好处是它抽象了与 Isolate 的通信细节,让我们可以专注于编写计算密集型的函数逻辑,而无需担心并发和消息传递的细节。它可以提高应用程序的性能,并让异步任务更加方便和易于管理。