两种方法 一种自己开启isolate线程,一种是使用flutter给封装好的compute方法
第一种
//yaml内导入
isolate: ^2.0.2
//开启线程数量 进行负载均衡
Future<LoadBalancer> loadBalancer = LoadBalancer.create(5, IsolateRunner.spawn);
//要实行的方法
Future<int> useLoadBalancer(model) async {
final lb = await loadBalancer;
int res = await lb.run<int, int>(selectedPlayerHandel(model), 1);
return res;
}
//必须是顶层方法 或者 静态方法
selectedPlayerHandel(model) {
GameAudioPlayerUtil.resetPlayer();
GameAudioPlayerUtil.playerHandle(model: model ?? GameMusicModel());
}
compute
使用
要使用compute,必须注意的有两点,一是我们的compute中运行的函数,必须是顶级函数或者是static函数,二是compute传参,只能传递一个参数,返回值也只有一个,我们先看看本例中的compute优化吧:
真的很简单,只用在使用的时候,放到compute函数中就行了。
var res = await compute(
selectedPlayerHandel(
gameMusicList[selectedMusic] ?? GameMusicModel()),
'selectedPlayerHandel');
如果发现有问题,请及时联系我,避免误人子弟...感谢!
网友评论