runAsync<Q, T> static method
Null safety
- ComputeCallback<
Q, T> run, - Q message,
- {IsolateExecutor? isolateExecutor,
- String debugLabel = 'CompletableIsolate'}
执行一个异步任务 该任务必须是一个全局方法或者静态方法
Implementation
static CompletableIsolate<T> runAsync<Q, T>(
ComputeCallback<Q, T> run,
Q message, {
IsolateExecutor? isolateExecutor,
String debugLabel = 'CompletableIsolate',
}) {
CompletableIsolate<T> completableFuture = CompletableIsolate<T>();
///初始化线程池
if (isolateExecutor == null) {
isolateExecutor = _isolateExecutor;
}
completableFuture._isolateExecutor0 = isolateExecutor;
/// 时间切片
final Flow flow = Flow.begin();
Timeline.startSync('$debugLabel: start', flow: flow);
final ReceivePort resultPort = ReceivePort();
final ReceivePort errorPort = ReceivePort();
Timeline.finishSync();
// 提交任务
completableFuture._asyncId =
isolateExecutor.execute<_CompletableIsolateConfiguration<Q, T>>(
CompletableIsolate._run,
_CompletableIsolateConfiguration<Q, T>(
callback: run,
message: message,
resultPort: resultPort.sendPort,
errorPort: errorPort.sendPort,
flowId: flow.id,
debugLabel: debugLabel,
),
);
/// 监听任务回调
resultPort.listen((result) {
Timeline.startSync('$debugLabel: end', flow: Flow.end(flow.id));
completableFuture.result = result;
resultPort.close();
errorPort.close();
Timeline.finishSync();
completableFuture._runCallback();
completableFuture._completeCallback();
});
errorPort.listen((errorData) {
Timeline.startSync('$debugLabel: end', flow: Flow.end(flow.id));
completableFuture.error = errorData[0];
completableFuture.stackTrace = errorData[1];
resultPort.close();
errorPort.close();
Timeline.finishSync();
completableFuture._errorCallback();
completableFuture._completeCallback();
});
return completableFuture;
}