随笔 - 31  文章 - 0  评论 - 1134  阅读 - 39万

异步编程练习

复制代码

 1class Program
 2    {
 3        static void Main(string[] args)
 4        {
 5            //异步委托方法一
 6            Func<intint> func = new Func<intint>(Square);
 7            IAsyncResult ar1= func.BeginInvoke(10nullnull);
 8            while (!ar1.IsCompleted)
 9                Console.WriteLine(func.EndInvoke(ar1));
10
11            //异步委托方法二
12            IAsyncResult ar2 = func.BeginInvoke(20nullnull);
13            ar2.AsyncWaitHandle.WaitOne();
14            Console.WriteLine(func.EndInvoke(ar2));
15
16            //异步委托方法三
17            IAsyncResult ar3 = func.BeginInvoke(30,
18                result =>
19                {
20                    if (result.IsCompleted)
21                        Console.WriteLine(func.EndInvoke(result));
22                }
,
23                func);
24
25            //后台线程方法
26            BackgroundWorker worker = new BackgroundWorker();
27            worker.DoWork += (s,e) => e.Result = Square((int)e.Argument);
28            worker.RunWorkerCompleted += (s,e) => Console.WriteLine(e.Result);
29            worker.RunWorkerAsync(40);
30
31            //多线程方法
32            Thread thread = new Thread(new ThreadStart(() => Console.WriteLine(Square(50))));
33            thread.Start();
34
35            Console.ReadLine();           
36        }

37
38        //可以为耗时的操作
39        private static int Square(int x)
40        {
41            return x * x;
42        }

43    }

https://files.cnblogs.com/guozili/CodeTimer.rar

 

复制代码
posted on   guozili  阅读(806)  评论(3编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2009年2月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
1 2 3 4 5 6 7
8 9 10 11 12 13 14

点击右上角即可分享
微信分享提示