当前位置:网站首页>C # basic 5-asynchronous
C # basic 5-asynchronous
2022-07-28 20:55:00 【W.C.Zeng】
asynchronous
Official document - Asynchronous model
Asynchrony is a very important concept in programming , C# The principle of implementing asynchrony is that the compiler converts the code into a state machine , Trace code execution to await Pause when and continue when the background job is completed .
if necessary I/O binding ( For example, request data from the network 、 Access the database or read and write to the file system ), You need to use asynchronous programming . You can also use CPU Binding code ( For example, perform costly calculations ), For writing asynchronous code , This is a good plan .
The following example CPU Binding code Asynchronous case of :
The main thread : Trigger the key to execute the background task -> count down -> Press any key to exit the program
Background thread : Get into -> count down -> sign out
Task class
Create an asynchronous task and execute
public static async Task SimpleWriteAsync()
{
string filePath = "simple.txt";
string text = $"Hello World!";
await File.WriteAllTextAsync(filePath, text);
}
static void Main()
{
SimpleWriteAsync().Wait();
}
about I/O Binding code , Waiting for one in async Return in method Task or Task The operation of .
about CPU Binding code , Wait for a use Task.Run Method to start the operation in the background thread .
using System;
using System.Threading.Tasks;
using System.Threading;
// 1 Declaration delegation
public delegate void onCountTime();
class Program
{
// Simulate some time-consuming and complex operations
static string CountTimer(string s, int start, int dt)
{
int counter = start;
while (counter > 0)
{
Console.WriteLine(s + counter);
Thread.Sleep(dt);
counter--;
}
return s + " End of the timing ";
}
// 4 Asynchronous event handler
static async void OnClicked()
{
string result = "";
Console.WriteLine("async OnClicked start");
// 4.1 Wait for asynchronous task Until the end of the mission
await Task.Run(() => {
result = CountTimer("task:", 3, 2000); });
// 4.2 Print the results
Console.WriteLine(result);
Console.WriteLine("async OnClicked end");
}
static void Main()
{
// Instantiate an instance of a button class
Button btn = new Button();
// 5 Bind the event handler for the click of the button
btn.Clicked += OnClicked;
// 6 ( Simulate the user pressing the key ) Manual call event
btn.CallClicked();
// 7 Process the task of pressing keys in the background The current thread continues execution
Console.WriteLine(CountTimer("main:", 3, 500));
Console.WriteLine("pressed any key to exit");
// Press any key to exit the program
Console.ReadKey();
}
// Button class
class Button
{
// 2 Claim event
public event onCountTime Clicked;
// 3 Call the event that the user presses the key
public void CallClicked()
{
Clicked?.Invoke();
}
}
}
// Print the results :
async OnClicked start
task:3
main:3
main:2
main:1
main: End of the timing
pressed any key to exit
task:2
task:1
task: End of the timing
async OnClicked end
边栏推荐
- 7/27 训练日志(位运算+后缀数组)
- Three steps to teach you unity serial communication
- The engineering practice of super large model was polished, and Baidu AI Cloud released the cloud native AI 2.0 solution
- C# 读取 CSV文件内数据,导入DataTable后显示
- Explain the camera in unity and its application
- Thinking and summary of R & D Efficiency
- Explain several mobile ways of unity in detail
- Redis review summary
- LVM logical volume
- Yum package management
猜你喜欢

How to balance security and performance in SQL?

Redis 3.0 source code analysis - data structure and object SDS list Dict

js网页黑白背景开关js特效

不懂就问,快速成为容器服务进阶玩家!

“当你不再是程序员,很多事会脱离掌控”—— 对话全球最大独立开源公司SUSE CTO...

Laser slam:logo-loam --- code compilation, installation and gazebo test

Unity gadget displays the file size of the resource directory

【服务器数据恢复】HP StorageWorks系列存储RAID5两块盘故障离线的数据恢复案例

研发效能的思考总结

"When you are no longer a programmer, many things will get out of control" -- talk to SUSE CTO, the world's largest independent open source company
随机推荐
Explain the life cycle function in unity in detail
js图片悬挂样式照片墙js特效
Job CE
flask 静态文件服务搭建
SQL audit tool self introduction owls
UE4.25 Slate源码解读
太空游戏第12课: 盾牌
Want to draw a picture that belongs to you? AI painting, you can also
About the title of linking to other pages
PL515 SOT23-5 单/双口 USB 充电协议端口控制器 百盛电子代理商
Sorting out problems in interface endpoint testing practice using Supertest
[1331. Array serial number conversion]
JS picture hanging style photo wall JS special effect
使用ORDER BY 排序
Two written interview questions about regular
How can enterprises successfully complete cloud migration?
Space shooting Lesson 15: props
Integrating database Ecology: using eventbridge to build CDC applications
一个程序员的水平能差到什么程度?尼玛,都是人才呀...
Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent