使用Isolate
的併發編程:與線程相似但不共享內存的獨立區域,僅經過消息進行通訊。編程
要使用Isolate
進行併發編程:bash
import 'dart:isolate';
複製代碼
該Library主要包含下面幾個類:併發
Isolate
:Dart執行上下文的隔離區。ReceivePort
:與SendPort
一塊兒,是隔離區之間惟一的通訊方式。SendPort
:將消息發送到其餘ReceivePort
。全部Dart代碼都在隔離區中運行,代碼只能訪問同一個隔離區的類和值。不一樣的隔離區能夠經過端口發送信息進行通訊。async
由spawn
操做提供的Isolate
對象將具備控制隔離所需的控制端口和功能。若有必要,可使用Isolate.Isolate
構造函數建立新的隔離對象,而無需使用這些功能。函數
要建立Isolate
,你可使用spawn
方法。必須爲spawn
方法提供一個帶有單個參數的「入口點」方法。 一般,此參數表示隔離應用於發送回通知消息的端口:ui
import 'dart:async';
import 'dart:isolate';
main(List<String> args) {
start();
print("start");
}
Isolate isolate;
int i =1;
void start()async{
//接收消息的主Isolate的端口
final receive = ReceivePort();
isolate = await Isolate.spawn(runTimer, receive.sendPort);
receive.listen((data){
print("Reveive : $data ; i :$i");
});
}
void runTimer(SendPort port){
int counter =0 ;
Timer.periodic(const Duration(seconds: 1), (_){
counter++;
i++;
final msg = "nitification $counter";
print("Send :$msg ;i :$i");
port.send(msg);
});
}
複製代碼
運行上面的例子控制檯的輸出爲:spa
start
Send :nitification 1 ;i :2
Reveive : nitification 1 ; i :1
Send :nitification 2 ;i :3
Reveive : nitification 2 ; i :1
Send :nitification 3 ;i :4
Reveive : nitification 3 ; i :1
複製代碼
在上面的例子中,使用start
方法來建立一個端口並生成一個Isolate
。spawn
使用了兩個參數,一個要執行的回調的函數runTimer
,和一個端口(SendPort
),回調能夠用來將消息發送回調用者。端口是你與Isolate
通訊的方式。這個例子將其設置爲單向通行(從隔離區發送信息到接收者),但它能夠是雙向的。在start
方法的最後是監聽來自定義isolate
的消息。線程
在控制檯的輸出中能夠看出,兩個Isolate
中打印的i的值並不一致,則說明Isolate
之間的內存並非共享的。code
在上面的例子中,Isolate
能夠一直進行下去。若是想Isolate
中止運行,可使用kill
方法。對象
void stop(){
print("kill isolate");
isolate?.kill(priority: Isolate.immediate);
isolate =null;
}
複製代碼
上面的代碼會殺死正在運行的Isolate
,並將引用置爲null
。 Isolate.immediate
的優先級將在最近的機會乾淨地關閉Isolate
。
還能夠暫停和恢復Isolate
的運行,分別對應Isolate
中的pause
方法和resume
方法。