C# 异步编程

本文通过两个具体的示例介绍了如何在 C# 中使用 BeginInvoke 和 EndInvoke 方法实现异步计算。第一个示例展示了轮询方法来检查异步操作的状态;第二个示例则改进了这一过程,通过回调函数在异步操作完成后自动处理结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子1:

    using System;  
          
     class Program  
        {  
            public delegate int CalculateDelegate(int min,int max);  
            static void Main(string[] args)  
            {  
                CalculateDelegate d = Calculate;  
                //为了简单,未检查输入是否数字  
                Console.WriteLine("请输入最小数字:");  
                int min = int.Parse(Console.ReadLine());  
                Console.WriteLine("请输入最大数字:");  
                int max = int.Parse(Console.ReadLine());  
                //public IAsyncResult BeginInvoke(  
                //  <输入和输出变量>,  
                //  AsyncCallback callback, object asyncState  
                //)  
                //第一部分是定义委托时确定的方法签名中的参数列表,没有参数时为空d.BeginInvoke(null, null);  
                //第二个参数callback是当异步调用结束时自动回调的函数  
                //第三个参数asyncState用于向第二个参数所确定的callback回调函数提供额外的信息  
                IAsyncResult ret = d.BeginInvoke(min, max, null, null);   
                Console.WriteLine("正在计算中,请耐心等待.....");  
                while (!ret.IsCompleted)  
                {  
                    Console.Write(".");  
                    System.Threading.Thread.Sleep(1000);  
                }  
               int count = d.EndInvoke(ret);  
               Console.WriteLine("/n计算完成。从{0}加到{1}的值为:{2}", min, max, count);  
                Console.ReadKey();  
            }  
            static int Calculate(int min,int max)  
            {  
                int count = 0;  
                for (int i = min; i < max; i++)  
                {  
                    count += i;  
                }  
                return count;  
            }  
        }  
例子2:

例子1使用轮询方法不断询问异步调用是否完成,会浪费不少CPU时间在循环等待上,可以让异步调用方法在结束时自动调用一个函数,并在这个函数中显示处理结果。

    using System;  
      class Program  
        {  
            public delegate int CalculateDelegate(int min, int max);  
            private static CalculateDelegate d = new CalculateDelegate(Calculate);  
            static void Main(string[] args)  
            {  
                Console.WriteLine("请输入最小数字:");  
                int min = int.Parse(Console.ReadLine());  
                Console.WriteLine("请输入最大数字:");  
                int max = int.Parse(Console.ReadLine());  
                //BeginInvoke()方法的第二个参数指定当异步调用结束时回调ShowMsg(),第三个参数传送给回调函数  
                IAsyncResult ret = d.BeginInvoke(min, max, ShowMsg, (min + "," + max));  
                Console.ReadKey();  
            }  
            static int Calculate(int min, int max)  
            {  
                int count = 0;  
                for (int i = min; i < max; i++)  
                {  
                    count += i;  
                }  
                return count;  
            }  
            static void ShowMsg(IAsyncResult result)  
            {  
                int count = d.EndInvoke(result);  
                string[] n = ((string)result.AsyncState).Split(',');  
                Console.WriteLine("从{0}加到{1}的和是{2}。", n[0], n[1], count);  
            }  
        }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值