前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Flutter 专题】93 图解 Dart 单线程实现异步处理之 Isolate (二)

【Flutter 专题】93 图解 Dart 单线程实现异步处理之 Isolate (二)

作者头像
阿策小和尚
发布2020-07-06 16:16:46
5870
发布2020-07-06 16:16:46
举报
文章被收录于专栏:阿策小和尚阿策小和尚

和尚刚学习了 Isolate 的部分基本用法,今天继续尝试 compute 及其使用方式;

Isolate

和尚之前了解到 ReceivePortSendPort 是成对出现的,是 Isolate 之间唯一的消息通讯的方式;

ReceivePort
代码语言:javascript
复制
abstract class ReceivePort implements Stream {
  external factory ReceivePort();

  external factory ReceivePort.fromRawReceivePort(RawReceivePort rawPort);

  StreamSubscription listen(void onData(var message),
      {Function onError, void onDone(), bool cancelOnError});

  void close();

  SendPort get sendPort;
}

简单分析源码可得,ReceivePort 中通过 get 获取一个 SendPort 对象,通过 SendPort 发送消息到 ReceivePort 中,之后再通过 listen 进行监听;

SendPort
代码语言:javascript
复制
abstract class SendPort implements Capability {
  void send(var message);

  bool operator ==(var other);

  int get hashCode;
}

SendPort 内容很简单,主要是通过 send 方法向 ReceivePort 传递消息;

Compute

和尚尝试了 Isolate 的基本用法,需要使用 ReceivePortSendPort 来进行消息通讯;而 Flutter 提供了更简单的 Compute Function

源码分析
代码语言:javascript
复制
Future<R> compute<Q, R>(isolates.ComputeCallback<Q, R> callback, Q message, { String debugLabel }) async {
  ...
  final Isolate isolate = await Isolate.spawn<_IsolateConfiguration<Q, FutureOr<R>>>(_spawn,
    _IsolateConfiguration<Q, FutureOr<R>>(
      callback, message,
      resultPort.sendPort,
      debugLabel, flow.id,
    ),
    errorsAreFatal: true,
    onExit: resultPort.sendPort,
    onError: errorPort.sendPort,
  );
  final Completer<R> result = Completer<R>();
  errorPort.listen((dynamic errorData) {
    ...
  });
  resultPort.listen((dynamic resultData) {
    ...
  });
  await result.future;
  Timeline.startSync('$debugLabel: end', flow: Flow.end(flow.id));
  resultPort.close();
  errorPort.close();
  isolate.kill();
  Timeline.finishSync();
  return result.future;
}

简单了解源码,Compute 实际是对 Isolate 的封装,Compute 是通过 Isolate.spawn() 方式来处理 Isolate 其中 compute() 方法中在通讯结束后自动进行 Isolate.kill() 销毁;且 compute() 直接返回内容,无需考虑 listen 监听等;

案例尝试

compute() 包含两个必填参数,第一个是定义新的 Isolate 的核心执行方法,第二个是函数对应的参数,可以是多个任意类型;因为 compute 实际是通过 Isolate.spawn() 来处理的,则对应的耗时方法也需要是在顶级 main 函数中或 static 方法;

代码语言:javascript
复制
_loadIsolateDate04() async {
  print('main Isolate, current Isolate = ${Isolate.current.hashCode}');
  print(await compute(getName, ''));
}

static String getName(String name) {
  print('new Isolate, current Isolate = ${Isolate.current.hashCode}');
  sleep(Duration(seconds: 2));
  return '阿策小和尚';
}

对于 compute() 的异常处理,可以通过 try-catch 进行捕获;

代码语言:javascript
复制
_loadIsolateDate05(bool isError) async {
  print('main Isolate, current Isolate = ${Isolate.current.hashCode}');
  try {
    print(await compute(_backgroundWork3, isError));
  } catch (e) {
    print(e);
  }
}

static _backgroundWork3(bool isError) async {
  print('new Isolate, current Isolate = ${Isolate.current.hashCode}');
  if (!isError) {
    return await Future.delayed(Duration(seconds: 2), () {
      return 'BackgroundWork delayed 2s -> currentTime -> ${DateTime.now().millisecondsSinceEpoch}';
    });
  } else {
    return await Future.error(ArgumentError.notNull('Input'));
  }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 阿策小和尚 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Isolate
    • ReceivePort
      • SendPort
      • Compute
        • 源码分析
          • 案例尝试
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档