zoukankan      html  css  js  c++  java
  • 简单的异步编程入门例子

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace 异步编程例子
    {
        class Program
        {
            public delegate int CaculateDelegate(int min, int max);
            static void Main(string[] args)
            {
                CaculateDelegate d=Caculate;
                Console.WriteLine("请输入:");
                int min = int.Parse(Console.ReadLine());
                Console.WriteLine("请输入");
                int max = int.Parse(Console.ReadLine());
                IAsyncResult ret = d.BeginInvoke(min,max,null,null);
                Console.WriteLine("正在计算中,请耐心等待.....");  
                while (!ret.IsCompleted)
                {
                    Console.Write(".");
                    Thread.Sleep(1000);
                }
                int count = (int)d.EndInvoke(ret);
                Console.WriteLine();
                Console.WriteLine("{0}+{1}={2}",min,max,count);
                Console.ReadKey();
            }
    
            public static int Caculate(int min, int max)
            {
                int count;
                Thread.Sleep(5000);
                count = min + max;
                return count;
            }
        }
    }
    

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

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace 异步编程例子
    {
        class Program
        {
            public delegate int CaculateDelegate(int min, int max);
            public static CaculateDelegate d = Caculate;
            static void Main(string[] args)
            {
                Console.WriteLine("请输入:");
                int min = int.Parse(Console.ReadLine());
                Console.WriteLine("请输入");
                int max = int.Parse(Console.ReadLine());
                IAsyncResult ret = d.BeginInvoke(min,max,ShowResult,(min+","+max));
                Console.WriteLine("正在计算中,请耐心等待.....");
                Console.ReadKey();
            }
    
            public static int Caculate(int min, int max)
            {
                int count;
                Thread.Sleep(5000);
                count = min + max;
                return count;
            }
    
            public static void ShowResult(IAsyncResult ret)
            {
                int count = (int)d.EndInvoke(ret);  
                string[] n = ((string)ret.AsyncState).Split(',');
                Console.WriteLine();
                Console.WriteLine("{0}+{1}={2}", n[0],n[1], count);
            }
        }
    }
    
  • 相关阅读:
    课后总结
    构建之法阅读笔记01
    软件工程周总结02
    开课博客
    二维数组最大子数组和
    大二下周总结四
    大二下周总结三
    定义一个整型数组,返回该数组中子数组和的最大值
    软件工程开课
    定义一个数组返回最大子数组的值(1)
  • 原文地址:https://www.cnblogs.com/jiekk/p/1977505.html
Copyright © 2011-2022 走看看