当前位置:网站首页>Dart asynchronous task
Dart asynchronous task
2022-06-30 09:02:00 【Silent Pinocchio】
Asynchronous task
Dart It's a single threaded task , Asynchronous operation supported
1.Isolate
2.Future
Isolate
adopt lsolate Implement asynchronous operations
void main() {
// Transmit the matched transmitter in the message receiver to isolate
Isolate.spawn(entryPoint, " Message sent ");
Isolate.spawn(entryPoint, " Message sent 2");
Isolate.spawn(entryPoint, " Message sent 3");
print(' Continue operation ');
}
void entryPoint(String msg) {
print(msg);
}
// Running results
Continue operation
Message sent
Message sent 2
Message sent 3
adopt Isolate A method can be executed asynchronously , We can do that entryPoint Method to perform some time-consuming tasks .
Usually in android In the development process , Time consuming tasks are not enough , It also requires interaction between threads , For example, the child thread requests data in UI Threads update pages and so on , Also in Dart We are asynchronous in Isolate And the Lord Isolate Conduct ( Let's call it that for the time being ) It also supports data interaction . thus , Receiver ReceivePort And that's what happened , As the name suggests, the receiver is used to receive messages , Of course there is a receiver There is also a transmitter SendPort, Every receiver There will be a corresponding transmitter .
void main(){
// Receiver
var receivePort = new ReceivePort();
receivePort.listen((message) {
print(message);
});
// The emitter
var sendPort = receivePort.sendPort;
sendPort.send(" Test message ");
}
// Print the results
Test message
Now the Isolate and receivePort Use in combination , To finish asynchronous communication .
For the sake of explanation , We are divided into Lord lsolate Hezi lsolate.
Since for communication , You need to live lsolate Hezi laolate Both need to hold each other's receiver , With the receiver Nature also has a transmitter .
Post the code first :
void main() {
late SendPort sendPort;
// Create a message receiver
var receivePort = new ReceivePort();
// Transmit the matched transmitter in the message receiver to isolate
Isolate.spawn(entryPoint, receivePort.sendPort);
// Read the message from the message receiver
receivePort.listen((message) {
// Determine message type
if (message is SendPort) {
print(' Main thread sender assignment ');
sendPort = message;
}
if (message is! SendPort) {
print(' Messages received by the main thread ↓↓↓↓');
print(message);
}
if (message == 1) {
sendPort.send(" This is the message sent by the main thread to the self thread ");
}
});
print(' Continue operation ');
}
void entryPoint(SendPort sendPort) {
// Create a receiver
var receivePort = new ReceivePort();
receivePort.listen((message) {
print(' Son isolate Monitored messages ' + message);
});
// Through the master lsolate The transmitter of To the Lord lsolate Sender lsolate The transmitter of
sendPort.send(receivePort.sendPort);
sleep(Duration(seconds: 5));
sendPort.send(" Messages sent by child threads ");
sleep(Duration(seconds: 5));
sendPort.send(1);
}
First create a child lsolate
And then the Lord lsolate The transmitter corresponding to the created receiver is transmitted to the child lsolate
Son lsolate Create a receiver , Then send the transmitter corresponding to the receiver to the master lsolate
Now? , Lord lsolate With its own receiver , Acceptable lsolate The news of , Some son lsolate My transmitter , Can be directed to child lsolate Send a message ; Son lsolate Have your own receiver , Can receive master lsolate Message sent , There are also masters lsolate My transmitter , You can think of the Lord lsolate Send a message ( This may be a bit of a detour , Need a good comb ).
thus , Lord lsolate and Son lsolate You can communicate .
Future
Future Object represents the result of an asynchronous operation Perform asynchronous tasks , Usually by then() To process the returned results
void main() {
Future future = Future.delayed(Duration(seconds: 3));
future.then((value) {
print(' Asynchronous task ');
});
print(' Synchronization task ');
}
// Execution results
Synchronization task
Asynchronous task
Here is the execution delay 3s The asynchronous task of , From the results, we can see that the execution of time-consuming tasks will not hinder main Method execution .
Besides Future It can also perform the serial execution of asynchronous tasks
void main() {
Future future = Future.delayed(Duration(seconds: 3)).then((value) {
print(' Asynchronous task 1');
});
Future future2 = future.then((value) {
sleep(Duration(seconds: 1));
print(' Asynchronous task 2');
});
future2.then((value) {
sleep(Duration(seconds: 1));
print(' Asynchronous task 2');
});
print(' Synchronization task ');
}
// Execution results
Synchronization task
Asynchronous task 1
Asynchronous task 2
Asynchronous task 2
async Used to indicate that the function is an asynchronous function , The object it returns is a Future object .
await Used to wait for the return result of time-consuming operation , This operation will block the following code .
Next, I'll use Future To execute a network request :
void main() {
print(' Method start execution ');
get().then((value) {
print(value);
});
print(' Method execution end ');
}
Future<Response> get() async {
// Network access
Response response = await Dio().get("https://www.wanandroid.com/banner/json");
return response;
}
// Execution results
Method start execution
Method execution end
{"data":[{"des.... Omit
It can be seen that asynchronous tasks will not hinder the execution of synchronous tasks .
Finally, I would like to add , stay Dart A task queue with priority tasks is provided in : Micro task queue
Task execution is a micro task queue priority
void main() {
var receivePort = new ReceivePort();
receivePort.listen((message) {
print(message);
});
receivePort.sendPort.send(" Test message ");
Future.microtask(() => {
print(' Micro task queue '),
sleep(Duration(seconds: 3))
});
}
// Execution results
Micro task queue
Test message

Personal notes , For reference only , If there is a problem , Welcome to correct , It's a great honor .
边栏推荐
- Treatment process record of Union Medical College Hospital (Dongdan hospital area)
- El input limit can only input numbers
- TiDB 6.0:让 TSO 更高效丨TiDB Book Rush
- Detailed explanation of rect class
- Duplicate entry '2' for key 'primary appears in JPA‘
- Esp32 things (VIII): music playing function of function development
- 维基媒体基金会公布新商业产品“维基媒体企业”首批客户
- Esp32 things (I): Preface
- File upload component on success event, add custom parameters
- Redis design and Implementation (VII) | publish & subscribe
猜你喜欢

Based on svelte3 X desktop UI component library svelte UI

Bind threads to run on a specific CPU logical kernel

技术管理进阶——管理者如何进行梯队设计及建设
![[data analysis and display]](/img/86/19260ee664769c98588d8b0783ef28.jpg)
[data analysis and display]

Do you want the dialog box that pops up from the click?

Pytorch BERT

Redis design and Implementation (I) | data structure & object

Maxiouassigner of mmdet line by line interpretation

Set, map and modularity

Rew acoustic test (II): offline test
随机推荐
Opencv learning notes -day4 image pixel reading and writing operations (array traversal and pointer traversal implementation, uchar vec3b data type and mat class functions mat:: at(), mat:: ptr())
Build a docker image of Henkel database from 0
[protobuf] protobuf generates cc/h file through proto file
Is the reverse repurchase of treasury bonds absolutely safe? How to open an account online
vite项目require语法兼容问题解决require is not defined
C#訪問SQL Server數據庫兩種方式的比較(SqlDataReader vs SqlDataAdapter)
Flink SQL custom connector
Detailed explanation of pytoch's scatter function
Invalid update: invalid number of sections. The number of sections contained in the table view after
Find the number that appears only once in the array
Comparaison de deux façons d'accéder à la base de données SQL Server (sqldatareader vs sqldataadapter)
Rew acoustic test (VI): signal and measurement
How to format an UTC date to use the Z (Zulu) zone designator in php?
Tidb 6.0: making Tso more efficient tidb Book rush
Introduction to the runner of mmcv
Interviewer: do you understand the principle of recyclerview layout animation?
JVM tuning related commands and explanations
Talking about the difference between kotlin collaboration and thread
[untitled]
Be careful of this hole in transmittable thread local