selvan selvan - 9 months ago 39
Dart Question

Isolate code didn't work as expected

Expected "Hello world" from simple isolate code shown below & didn't work.

import 'dart:async';
import 'dart:isolate';

var mainReceivePort = new ReceivePort();

main() async {
await Isolate.spawn(hello, null);
await for (var msg in mainReceivePort) {
print(msg);
return;
}
}

hello(_) async {
var sendPort = mainReceivePort.sendPort;
sendPort.send("Hello world");
}


When following changes were made to the code, it works as intended

import 'dart:async';
import 'dart:isolate';

var mainReceivePort = new ReceivePort();

main() async {
await Isolate.spawn(hello, mainReceivePort.sendPort);
await for (var msg in mainReceivePort) {
print(msg);
return;
}
}

hello(sendPort) async {
sendPort.send("Hello world");
}


Looking for clues. any thoughts?

Answer Source

In the first example sendPort is not connected to the main isolate, it exists only in the spawned isolate.

This code is executed in both isolates

var mainReceivePort = new ReceivePort();

and each isolate gets a different mainReceivePort instance which are not connected in any way.

In the 2nd example the sendPort connected to mainReceivePort of the main isolate is passed to the spawned isolate and messages passed to it will be received by the connected mainReceivePort of the main isolate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download