简单的异步编程入门例子

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);

        }

    }

}

你可能感兴趣的:(编程)