A Simple Example Practice in Async Programming
本文逻辑
介绍基本概念,实现一个小的Async Programming例子, 并对一些常用的概念作一些介绍
概念介绍
查看: [Programming IL] Delegates
实例逻辑
利用Delegate - BeginInvoke的两种调用方式进行编程
- CallBack 回调式
- Sequential 顺序执行
实例代码
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Runtime.Remoting.Messaging;
6:
7: namespace AsyncPatterns
8: {
9: public class EventAsyncSample
10: {
11: private void OnCallBack(IAsyncResult result)
12: {
13: AsyncTargetCaller callback = (AsyncTargetCaller)((AsyncResult)result).AsyncDelegate;
14:
15: Int64 number = (int)result.AsyncState;
16: number = callback.EndInvoke(result);
17:
18: Console.WriteLine("The Result Is: {0}", number);
19: }
20:
21: /// <summary>
22: /// Call the target and invoke a method outside when done
23: /// </summary>
24:
25: public void AsyncCallTarget()
26: {
27: AsyncTargetCaller caller = new AsyncTargetCaller(AsyncTarget.Sum);
28:
29: AsyncCallback callback = new AsyncCallback(OnCallBack);
30: int number = int.MaxValue;
31: caller.BeginInvoke(number, callback, number);
32:
33: Console.WriteLine("Begin To Call the AsyncTarget");
34: }
35:
36: /// <summary>
37: /// No Callback, get all done in a single method
38: /// </summary>
39:
40: public void WaitAsyncCallTarget()
41: {
42: AsyncTargetCaller caller = new AsyncTargetCaller(AsyncTarget.Sum);
43: IAsyncResult result = caller.BeginInvoke(int.MaxValue, null, null);
44:
45: while (!result.IsCompleted)
46: {
47: result.AsyncWaitHandle.WaitOne(1000);
48: Console.WriteLine("Waiting for you");
49: }
50:
51: Console.WriteLine("WaitAsyncCallTarget Result: {0}", caller.EndInvoke(result));
52: }
53: }
54:
55: /// <summary>
56: /// The target to be called
57: /// </summary>
58: public class AsyncTarget
59: {
60: public static Int64 Sum(Int32 number)
61: {
62: Console.WriteLine("Entering the Sum UpdateMilestone");
63: Int64 m_Temp = 0;
64: for (int i = number; i > 0; i--)
65: {
66: m_Temp += i;
67: }
68: return m_Temp;
69: }
70: }
71:
72: /// <summary>
73: /// A delegatet to call the method
74: /// </summary>
75: /// <param name="number"></param>
76: /// <returns></returns>
77: public delegate Int64 AsyncTargetCaller(int number);
78:
79: }
当我们调用WaitAsyncCallTarget 输出结果:
当调用AsyncCallTarget 输出结果
我们一般会在在如下情况使用异步编程.
- 加载大容量数据
- 下载大量数据
- 网络通信和WebService调用
而这些方法都是可以使用异步编程来达到效果, 同时,在.Net Framework中一些处理也集成了处理,比如:流,WebService, WebClient等
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端