当前位置:网站首页>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 .
边栏推荐
- Understanding of MVVM and MVC
- How can I get the discount for opening a securities account? Is online account opening safe?
- asdsadadsad
- Flink SQL custom connector
- Esp32 things (3): overview of the overall system design
- Wechat development tool (applet)
- Redis design and Implementation (VII) | publish & subscribe
- QT connection to Shentong database
- [JPEG] how to compile JPEG turbo library files on different platforms
- Vite project require syntax compatibility problem solving require is not defined
猜你喜欢
QT connection to Shentong database
Talk about the job experience of kotlin cooperation process
Redis design and Implementation (III) | interaction between server and client (event IO model)
Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu
Opencv learning notes-day6-7 (scroll bar operation demonstration is used to adjust image brightness and contrast, and createtrackbar() creates a scroll bar function)
Does the oscilloscope probe affect the measurement of capacitive load?
[data analysis and display]
vim 从嫌弃到依赖(21)——跨文件搜索
Qt连接神通数据库
Wechat development tool (applet)
随机推荐
【付费推广】常见问题合集,推荐榜单FAQ
基于Svelte3.x桌面端UI组件库Svelte UI
Tidb 6.0: making Tso more efficient tidb Book rush
vite項目require語法兼容問題解决require is not defined
Esp32 things (x): other functions
Metasploit practice - SSH brute force cracking process
[cmake] make command cannot be executed normally
[paid promotion] collection of frequently asked questions, FAQ of recommended list
Installation, use and explanation of vulnerability scanning tool OpenVAS
CUDA realizes L2 European distance
vim 从嫌弃到依赖(21)——跨文件搜索
Opencv learning notes-day5 (arithmetic operation of image pixels, add() addition function, subtract() subtraction function, divide() division function, multiply() multiplication function
[untitled]
Rew acoustic test (IV): test principle of rew
[protobuf] protobuf generates cc/h file through proto file
Anchorgenerator for mmdet line by line interpretation
Rew acoustic test (I): microphone calibration
[kotlin collaboration process] complete the advanced kotlin collaboration process
C accesses mongodb and performs CRUD operations
Torchvision loads the weight of RESNET except the full connection layer