当前位置:网站首页>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
边栏推荐
- "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
- 到底为什么不建议使用SELECT * ?
- Network shell
- Space game Lesson 12: shield
- 一文了解 Rainbond 云原生应用管理平台
- Ask if you don't understand, and quickly become an advanced player of container service!
- 云原生编程挑战赛火热开赛,51 万奖金等你来挑战!
- How to make the design of governance structure more flexible when the homogenization token is combined with NFT?
- Record an error in runtime. Getruntime().Exec ("command")
- Three deletion strategies and eviction algorithm of redis
猜你喜欢
Alibaba cloud MSE supports go language traffic protection
全链路灰度在数据库上我们是怎么做的?
Space shooting Lesson 15: props
h5微信射击小游戏源码
第六七八次作业
What is "security"? Volvo tells you with its unique understanding and action
Unity makes prefabricated bodies with one key and modifies prefabricated bodies with one key
“当你不再是程序员,很多事会脱离掌控”—— 对话全球最大独立开源公司SUSE CTO...
How to balance security and performance in SQL?
Integrating database Ecology: using eventbridge to build CDC applications
随机推荐
Read the recent trends of okaleido tiger and tap the value and potential behind it
[1331. Array serial number conversion]
prometheus配置alertmanager完整过程
Job CE
Integrating database Ecology: using eventbridge to build CDC applications
十七年运维老兵万字长文讲透优维低代码~
Three deletion strategies and eviction algorithm of redis
融合数据库生态:利用 EventBridge 构建 CDC 应用
想画一张版权属于你的图吗?AI作画,你也可以
Oracle库访问很慢,是什么原因?
js win7透明桌面切换背景开始菜单js特效
Algorithm interview high frequency problem solving guide [1]
既要便捷、安全+智能,也要颜值,萤石发布北斗星人脸锁DL30F和极光人脸视频锁Y3000FV
How can enterprises successfully complete cloud migration?
太空射击第10课: Score (繪畫和文字)
太空游戏第12课: 盾牌
卡通js射击小游戏源码
Beautiful blue background form input box style
System. ArgumentException: Object of type ‘System. Int64‘ cannot be converted to type ‘System.Int32‘
Use order by to sort