I just tried simple asynchronous operations implemented by Future and async-await, but what about longer asynchrony? For Android, a new thread can be opened for separate processing, and the corresponding Dart can be processed using the Isolate.

Isolate

The Isolate is the implementation of the Dart concurrency mode. It is similar to Thread in Android, but fundamentally different from Thread. Thread can share memory, while the Isolate cannot.

All Dart codes are executed within the Isolate. The Code can only use the contents of the same Isolate. The Isolate has its own memory and event loop mechanism. Different ISOLatets are isolated in memory. Therefore, they can only send messages to different ISOLatets through the Port mechanism.

Isolate the creation of

Spawn/spawnUri is used to create objects.

Isolate.spawn()
external static Future<Isolate> spawn<T>( void entryPoint(T message), T message, {bool paused: False, bool errorsAreFatal, SendPort onExit, SendPort onError, @since ("2.3") String debugName});Copy the code

To understand the source code, the parameters required for Spawn include entryPoint and T, which require time-consuming operation. Any type of message data can be passed in the Isolate.

_loadIsolateDate() async {
  await Isolate.spawn(_backgroundWork, ReceivePort().sendPort);
}

static _backgroundWork(SendPort sendPort) {
  sendPort.send('BackgroundWork -> currentTime -> ${DateTime.now().millisecondsSinceEpoch}');
}
Copy the code
Isolate.spawnUri()
external static Future<Isolate> spawnUri( Uri uri, List<String> args, var message, {bool paused: false, SendPort onExit, SendPort onError, bool errorsAreFatal, bool checked, Map<String, String> environment, @Deprecated('The packages/ dir is not supported in Dart 2') Uri packageRoot, Uri packageConfig, Bool automaticPackageResolution: false, @ Since (" 2.3 ") String debugName});Copy the code

Briefly understand the source code. SpawnUri requires three necessary parameters, uri is the path of other Isolate code files; List args is the list of parameters to pass, message dynamic message, usually SendPort;

_loadIsolateDate03() async { ReceivePort receivePort = ReceivePort(); await Isolate.spawnUri(new Uri(path: "./utils/second_isolate.dart"), ['params01, params02, params03'], receivePort.sendPort); Receiveport.listen ((val) => print('listen -> [$val] ')); }Copy the code

Isolate the communication

The Isolate enables multi-core cpus to process time-consuming operations. Because memory is not shared, messages are transmitted through ports. Port messaging is also asynchronous;

One-way communication

Ports usually come in pairs. They are ReceivePort for receiving and SendPort for sending. ReceivePort can also generate its own SendPort; Simply pass SendPort to other ISOLates.

_loadIsolateDate01() async { ReceivePort receivePort = ReceivePort(); await Isolate.spawn(_backgroundWork, receivePort.sendPort); Receiveport.listen ((val) => print('listen -> [$val] ')); } static _backgroundWork(SendPort sendPort) async { sendPort.send( 'BackgroundWork -> currentTime -> ${DateTime.now().millisecondsSinceEpoch}'); Future.delayed(Duration(seconds: 3), () { return sendPort.send( 'BackgroundWork delayed 3s -> currentTime -> ${DateTime.now().millisecondsSinceEpoch}'); }); }Copy the code

Two-way communication

Two-way communication is the same as one-way communication, the SendPort of both sides can be transmitted to each other;

_loadIsolateDate02() async { ReceivePort receivePort = ReceivePort(); var sendPort; await Isolate.spawn(_backgroundWork2, receivePort.sendPort); receivePort.listen((val) { if (val is SendPort) { sendPort = val as SendPort; Print (" two-way communication established successfully "); } print("Isolate Recevie Data -> [$val] "); if (sendPort ! = null) { sendPort.send('_loadIsolateDate02 -> currentTime -> ${DateTime.now().millisecondsSinceEpoch}'); }}); } static _backgroundWork2(SendPort sendPort) async { ReceivePort receivePort = new ReceivePort(); Receiveport.listen ((val) {print("Background Isolate Receive Data -> [$val]"); }); sendPort.send('BackgroundWork -> currentTime -> ${DateTime.now().millisecondsSinceEpoch}'); sendPort.send(receivePort.sendPort); Future.delayed(Duration(seconds: 2), () { return sendPort.send('BackgroundWork delayed 2s -> currentTime -> ${DateTime.now().millisecondsSinceEpoch}'); }); Future.delayed(Duration(seconds: 5), () { return sendPort.send(receivePort.sendPort); }); }Copy the code

Isolate the destruction

The Isolate is like a small space in a machine and has its own memory block. Therefore, you need to close it and destroy it after using it.

isolate.kill(priority: Isolate.immediate);
Copy the code

Tips

Q: Invalid argument(s): isolate. spawn expects to be passed a static or top-level function

When creating the Isolate, the following error occurs.

A:

The message parameter method in isolate.spawn needs to be set to static or placed in the main() entry;


Due to the lack of space and test cases, I divided it into two small blogs to learn about THE Isolate. The cognition of asynchronism is not deep enough. If there is a mistake, please guide!

Source: Young Monk Atze