【发布时间】:2021-11-22 06:25:04
【问题描述】:
我在使用 Isolate.spawn() 时遇到了 Dart 的泛型类型的问题。我觉得这应该可行,但它没有。
我正在尝试围绕 Isolate.spawn() 编写一个类型安全(-ish)的包装器,以确保我将有效类型传递给我想在另一个线程中运行的函数(输入参数),以及我从此函数获得的结果值的类型(输出结果值)。
所以,我创建了InputType 和OutputType 虚拟类作为我的输入和输出类型。 thread 函数是我想在另一个线程中运行的函数。 run 函数是实际的包装器:它应该接受在另一个线程中运行的函数,它是参数。
import 'dart:async';
import 'dart:isolate';
typedef Callback<I, R> = Future<R> Function(I input);
class Config<I, R> {
final Callback<I, R> callback;
final I arg;
final SendPort port;
Config(this.callback, this.arg, this.port);
}
class InputType {
int arg;
InputType(this.arg);
}
class OutputType {
String str;
OutputType(this.str);
}
Future<R> _spawn<I, R>(Config<I, R> conf) async {
print("callback: ${conf.callback}");
return await conf.callback(conf.arg);
}
void run<I, R>(Callback<I, R> func, I arg) async {
ReceivePort resultPort = ReceivePort();
Config<I, R> conf = Config<I, R>(func, arg, resultPort.sendPort);
Isolate thread = await Isolate.spawn<Config<I, R>>(_spawn, conf);
// ...
}
Future<OutputType> thread(InputType input) async {
print("running in isolate");
return OutputType("Hello, arg was: ${input.arg}");
}
void main() async {
print("runtime");
run<InputType, OutputType>(thread, InputType(123));
}
我遇到的结果错误:
$ dart isolate.dart
runtime
Unhandled exception:
type '(InputType) => Future<OutputType>' is not a subtype of type '(dynamic) => Future<dynamic>'
#0 _spawn (file:///home/antek/dev/dart/tests/generic/isolate.dart:24:27)
#1 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:286:17)
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
^C
错误实际上来自这一行:
print("callback: ${conf.callback}");
有人知道如何解决这个问题吗?
【问题讨论】:
标签: dart dart-isolates