当前位置:网站首页>Continue to have a fever. Try the asynchronous operation of dart language. The efficiency is increased by 500%
Continue to have a fever. Try the asynchronous operation of dart language. The efficiency is increased by 500%
2022-06-24 07:41:00 【Tangge engages in development】
Preface
I posted an article yesterday 《Dart Development server , I have a fever ( SAO ) 了 》, Thank you for reading the homepage .
I have a fever today , And how to use it Dart Asynchronous operation of language . Speaking of asynchronous operation , play NodeJS My classmates smiled knowingly , This is our housekeeping skill . play PHP, JAVA My classmates will have a look , It means that we just look and don't talk .
Before the code demonstration , Let's start with a scenario . Suppose I have some beautiful sisters , I want to send an email to them , Show love . In this process , What the code needs to do :
- Receiving request
- Save my email content to the database
- They also need to send the email content to their mailbox .
- Return results
In the process , What I care about is how long it takes to send an email , Because I have too many sisters , If an email takes too long , I can't take care of others . It's up there 4 In one step , Which steps will take time ?
Obviously ,1 and 4 Basically, it is absolutely time-consuming ,2 It's going to take some time , But the time is short ,3 It takes the longest , Because it involves network transmission , Too many uncontrollable factors .
What synchronization code looks like
Let's simulate the above process by synchronizing the code .
Suppose that saving information to the database requires 1 second , Sending an email to the other party's mailbox requires 5 second , Overall, it should be 6 Some more .
import 'dart:io';
main() {
acceptRequest(); // Accept the request
saveToDb(); // Save to database , Not too time consuming , Suppose you need 1 second
sendLetter(); // Send mail to the other party's mailbox , It's very time consuming , Suppose you need 5 second
returnRes(); // Return results
}
void acceptRequest() {
print(DateTime.now().toString() + ' Accept the request ');
}
void saveToDb() {
sleep(Duration(seconds: 1));
print(DateTime.now().toString() + ' Database saved successfully ');
}
void sendLetter() {
sleep(Duration(seconds: 5));
print(DateTime.now().toString() + ' Email sent successfully ');
}
void returnRes() {
print(DateTime.now().toString() + ' Return results ');
}Execute it , Get the printed results
2021-06-29 16:40:44.993785 Accept the request 2021-06-29 16:40:46.000240 Database saved successfully 2021-06-29 16:40:51.002400 Email sent successfully 2021-06-29 16:40:51.002400 Return results
A simple calculation , From accepting the request to returning the result , The total time is 6 About seconds , In line with expectations .
What does asynchronous code look like
Said just now , I have many beautiful sisters , An email takes so long , How long will it take for so many sisters , Can you hurry up ?
Of course , The code is as follows :
main() async {
acceptRequest(); // Accept the request
await saveToDb(); // Save to database , Not too time consuming , need 1 second
sendLetter(); // Send mail to the other party's mailbox , It's very time consuming , need 5 second
returnRes(); // Return results
}
void acceptRequest() {
print(DateTime.now().toString() + ' Accept the request ');
}
void saveToDb() async {
await Future.delayed(Duration(seconds: 1));
print(DateTime.now().toString() + ' Database saved successfully ');
}
void sendLetter() async {
await Future.delayed(Duration(seconds: 5));
print(DateTime.now().toString() + ' Email sent successfully ');
}
void returnRes() {
print(DateTime.now().toString() + ' Return results ');
}Execute it , Get the print results
2021-06-29 16:47:46.931323 Accept the request 2021-06-29 16:47:47.956545 Database saved successfully 2021-06-29 16:47:47.959539 Return results 2021-06-29 16:47:52.960542 Email sent successfully
This result , But I need to pay attention . There are two points to note :
- From receiving the request to returning the result , All in all 1 About seconds
- Email sent successfully , It appears after the returned result , interval 5 second
Why is that ? In fact, this is Dart The charm of language asynchronous operation .
Dart By default, tasks are executed in code order .
But when it comes to sendLetter It's time , Find out it's a async Asynchronous operations , And don't wait for it , Then just skip him , Implemented the following returnRes , So it prints out Return results
After returning the result , If it is a browser request , Then the browser request ends directly . But it's not over ,Dart Continued to execute the just skipped sendLetter, So I finally printed out Email sent successfully
As a whole , I sent an email this time , It only took 1 Second , And before it was 6 Second. , This efficiency improvement , A good 500%
Mm-hmm , That's great , I can take care of more sisters .
await async What the hell is it
The sharp eyed students may have seen , In the above code
main() async {
acceptRequest(); // Accept the request
await saveToDb(); // Save to database , Not too time consuming , need 1 second
sendLetter(); // Send mail to the other party's mailbox , It's very time consuming , need 5 second
returnRes(); // Return results
}saveToDb Save database And sendLetter Sending oil prices is a time-consuming operation , Why? saveToDb I added await ?
This is because , saveToDb It's also asynchronous operation , If not await , It will look like sendLetter Just like sending email , Be skipped first , After the browser returns the result , To be carried out . This creates a problem , If writing to the database fails , But you've told the user that it was successful , Isn't that embarrassing ?
therefore , saveToDb I added await, tell Dart Although this code is asynchronous , You need to synchronize .
summary
When an operation is very time-consuming , We can set it to be asynchronous async, First return information to the user , Take your time .
If you want to make an asynchronous operation synchronous , You can add keywords await, Indicates that I am willing to wait for the asynchronous result .
Dart Provides a mechanism for asynchronous operation , We can use them easily .
play NodeJS I cried , Someone stole his housekeeping skills .
边栏推荐
- MySQL case: analysis of full-text indexing
- 与(&&)逻辑或(||),动态绑定结合三目运算
- What is a CC attack? How to judge whether a website is attacked by CC? How to defend against CC attacks?
- bjdctf_ 2020_ babystack
- Pyhton crawls to Adu (Li Yifeng) Weibo comments
- PNAs: Geometric renormalization reveals the self similarity of multi-scale human connectome
- [wustctf2020] climb
- What is the mentality of spot gold worth learning from
- Tencent cloud security and privacy computing has passed the evaluation of the ICT Institute and obtained national recognition
- MFC multithreaded semaphore csemaphore critical area and mutually exclusive events
猜你喜欢

The first common node of two linked lists_ The entry of the link in the linked list (Sword finger offer)

Analog display of the module taking software verifies the correctness of the module taking data, and reversely converts the bin file of the lattice array to display
![[WordPress website] 5 Set code highlight](/img/01/f669b70f236c334b98527a9320400c.png)
[WordPress website] 5 Set code highlight

Alibaba cloud full link data governance

Buuctf misc grab from the doll

What are the dazzling skills of spot gold?
![buuctf misc [UTCTF2020]docx](/img/e4/e160f704d6aa754e85056840e14bd2.png)
buuctf misc [UTCTF2020]docx
![LeetCode 515 在每个数行中找最大值[BFS 二叉树] HERODING的LeetCode之路](/img/16/011ba3aef1315c39526daac7e3ec89.png)
LeetCode 515 在每个数行中找最大值[BFS 二叉树] HERODING的LeetCode之路
![[Proteus] Arduino uno + ds1307+lcd1602 time display](/img/96/d8c1cacc8a633c679b1a58a1eb8cb9.png)
[Proteus] Arduino uno + ds1307+lcd1602 time display
╯︵ ┻━┻](/img/26/6986a8ae6c00eb2431a082dc0ff978.png)
[DDCTF2018](╯°□°)╯︵ ┻━┻
随机推荐
相机标定(标定目的、原理)
图形技术之管线概念
湖北专升本-湖师计科
What is automated testing? What software projects are suitable for automated testing?
相機標定(標定目的、原理)
[机缘参悟-29]:鬼谷子-内揵篇-与上司交往的五种层次
Quickly set up PgSQL for serverless
Combine with (& &) logic or (||), dynamic binding and ternary operation
In the era of industrial Internet, there are no more centers in the real sense, and these centers just turn tangible into intangible
6000多万铲屎官,捧得出一个国产主粮的春天吗?
UE常用控制台命令
[OGeek2019]babyrop
使用SystemParametersInfo访问用户界面设置
Global and Chinese markets for maritime transport of perishable goods 2022-2028: Research Report on technology, participants, trends, market size and share
Pyhton crawls to Adu (Li Yifeng) Weibo comments
[learn FPGA programming from scratch -41]: vision chapter - Moore's era and Moore's law and the arrival of the post Moore Era
Dichotomous special training
How VPN works
[DDCTF2018](╯°□°)╯︵ ┻━┻
C# Lambda