当前位置:网站首页>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 .
边栏推荐
- Lend you a pair of insight, Frida native trace
- Global and Chinese market of offshore furnaces 2022-2028: Research Report on technology, participants, trends, market size and share
- atguigu----15-内置指令
- Bjdctf 2020 Bar _ Babystack
- L2tp/ipsec one click installation script
- [GUET-CTF2019]zips
- [MRCTF2020]千层套路
- Group policy disables command prompt bypass
- buuctf misc [UTCTF2020]docx
- Maxcompute remote connection, uploading and downloading data files
猜你喜欢

RDD基础知识点
![Selector (>, ~, +, [])](/img/7e/2becfcf7a7b2e743772deee5916caf.png)
Selector (>, ~, +, [])

Camera calibration (calibration purpose and principle)
![[WUSTCTF2020]alison_ likes_ jojo](/img/a9/dcc6f524772cd0b8781289cbaef63f.png)
[WUSTCTF2020]alison_ likes_ jojo

LeetCode 207:课程表(拓扑排序判断是否成环)

PIP install XXX on the terminal but no module named XXX on pycharm

bjdctf_2020_babystack

RDD basic knowledge points

More than 60 million shovel excrement officials, can they hold a spring of domestic staple food?
![buuctf misc [UTCTF2020]docx](/img/e4/e160f704d6aa754e85056840e14bd2.png)
buuctf misc [UTCTF2020]docx
随机推荐
[image feature extraction] image feature extraction based on pulse coupled neural network (PCNN) including Matlab source code
[vulhub shooting range]] ZABBIX SQL injection (cve-2016-10134) vulnerability recurrence
How VPN works
MaxCompute远程连接,上传、下载数据文件操作
How to delete / select an input method on your computer
[WUSTCTF2020]alison_ likes_ jojo
Obtain the package name, application name, icon, etc. of the uninstalled APK through packagemanager. There is a small message
Lend you a pair of insight, Frida native trace
LeetCode 515 在每个数行中找最大值[BFS 二叉树] HERODING的LeetCode之路
The seminar on "global IPv6 development and outlook 2020-2021" was held in Beijing
Counter attack from outsourcing to big factories! Android has been developed for 5 years, and after a year of dormancy, it has tried to become an offer harvester. Tencent has a fixed salary of 20*15
使用SystemParametersInfo访问用户界面设置
与(&&)逻辑或(||),动态绑定结合三目运算
Only two lines are displayed, and the excess part is displayed with Ellipsis
Description of module data serial number positioning area code positioning refers to GBK code
Session & cookie details
Unity Culling 相关技术
[WUSTCTF2020]alison_likes_jojo
How can win11 set the CPU performance to be fully turned on? How does win11cpu set high performance mode?
[wustctf2020] climb