I wished to create an Isolate in Dart that I could pause and resume programmatically. This is the code that I used.
import 'dart:io';
import 'dart:isolate';
void main() async {
print("Starting isolate");
Isolate isolate;
ReceivePort receivePort = ReceivePort();
isolate = await Isolate.spawn(run, receivePort.sendPort);
print("pausing");
Capability cap = isolate.pause(isolate.pauseCapability);
sleep(Duration(seconds: 5));
print("Resuming");
isolate.resume(cap);
}
void run(SendPort sendPort) {
sleep(Duration(seconds: 2));
print("Woke up, 1");
sleep(Duration(seconds: 2));
print("Woke up, 2");
sleep(Duration(seconds: 2));
print("Woke up, 3");
sleep(Duration(seconds: 2));
print("Woke up, 4");
sleep(Duration(seconds: 2));
print("Woke up, 5");
}
I'm getting an O/P like
Starting isolate
pausing
Woke up, 1
Woke up, 2
Resuming
Woke up, 3
Woke up, 4
Woke up, 5
But I want to achieve
Starting isolate
pausing
<--- 5 second delay --->
Resuming
Woke up, 1
Woke up, 2
Woke up, 3
Woke up, 4
Woke up, 5
But even after calling pause(), the Isolate keeps running. I found this answer and it said that it was because of the infinite loop in their case but I'm not using any loop. So what am I doing wrong here?