flutter 多线程 线程池 新操作

感觉不我之前写的方法确实是有点问题 于是研究了半天找了一个插件

1.添加依赖:

worker_manager

2.main函数在runApp之前先初始化  warmup函数也可以自定义设置线程池数 isolate数

 3.正文

//算法2

    Executor executor= Executor();


    while(i<length-1){

      String mid=idList[i];
      String client=clientList[i];

      i++;
      String mainUrl='https://maplestory.io/api/${client}map';
      String url = '${mainUrl}/${mid}/bgm';

      List params=[file,url,mid];

//      print('正在下载第$i/${length}个Map映射url ${mid}->${client}  总线程数:${currentThreadNum}/${maxThreadNum} ');


      executor.execute(arg1:params,fun1: doComputeWriteRedirectUrl).next(
        onValue: (value) async {
          await Future.delayed(Duration(microseconds:(Random().nextDouble()*1000*100).floor()));
          taskIndex++;
          print('完成下载第$taskIndex/${length}个Map映射url ${mid}->${client} ');
          if(taskIndex==length){
            print('任务完成  $taskIndex/${length}');
        }

          //currentThreadNum--;
        },
        onError: (error) async {
          print(error);
          print('错误下载第$taskIndex/${length}个Map映射url ${mid}->${client}');

          await Future.delayed(Duration(microseconds:(Random().nextDouble()*1000*100).floor()));
          //currentThreadNum--;
        }

      );

    }



    //endregion
    print('任务分配结束');

改良x2

onvalue异步会出现同时写入文本的情况 导致写入的时候部分文本不完整 导致严重错误


      Executor().execute(
          arg1:params,
          fun1: doComputeWriteRedirectUrl
      ).next(
        onValue: (resStr){


          if(!resStr.toString().contains('=')){
            print('一个出错 ${resStr}');
          }

          //compute(doComputeWriteEa,[resStr,file]);
          //等待时间防止同时?
          //await Future.delayed(Duration(microseconds:(Random().nextDouble()*1000*100).floor()));
          //Executor().execute(priority: WorkPriority.high,arg1:[resStr,file],fun1:doComputeWriteEa );
          doComputeWriteEa([resStr,file]);
          //好像不设置异步能解决这个问题

          taskIndex++;
          print('完成下载第$taskIndex/${length}个Map映射url ${mid}->${client}   ${(resStr as String ).replaceAll('\n', '')}');
          if(taskIndex==length){
            print('任务完成  $taskIndex/${length}');
        }

          //currentThreadNum--;
        },
        onError: (error) async {
          print(error);
          print('错误下载第$taskIndex/${length}个Map映射url ${mid}->${client}');

          await Future.delayed(Duration(microseconds:(Random().nextDouble()*1000*100).floor()));
          //currentThreadNum--;
        }

      );

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值