C#委托异步调用

时间:2022-06-10 05:56:50

废话不多说,,直接上代码(PS:我就喜欢简单、直接、粗暴)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 异步调用委托
{
    class Program
    {
        static void Main(string[] args)
        {
            MyDelegate md = new MyDelegate(sum);

            #region 一般的程序调用
            //int s = md(1, 20);
            //Console.WriteLine("Sum is: {0}", s);
            #endregion

            #region 直接通过调用异步委拖获取返回值,会阻塞主线程
            // 开始执行异步调用,使用了线程池,为线程
            //IAsyncResult res = md.BeginInvoke(1,30,null,"test");

            //// 在这里可以进行其它操作
            //Console.WriteLine("在这里可以进行其它操作的哦~");

            //// 这种方式获取返回值会中断主线程的执行
            //int s = md.EndInvoke(res);
            //Console.WriteLine("Sum is: {0}", s);
            #endregion

            #region 通过回调函数实现异步委托返回值,不阻塞主线程
            IAsyncResult res = md.BeginInvoke(1, 30, CallBack, "Test");
            #endregion

            //子线程你慢慢玩,我一边等你,一边做点事,你做玩完就一起回家
            int i = 0;
            while (!res.IsCompleted)
            {             
                Console.WriteLine("主线程继续执行..." + (i++ % 100).ToString());
                System.Threading.Thread.Sleep(100);
            }

            Console.ReadKey();
        }

        // 实际的计算方法 - 假设非常耗时
        private static int sum(int fromNum, int toNum)
        {
            int sum = 0;
            for (int i = fromNum; i < toNum; i++)
            {
                sum++;
                Thread.Sleep(100);
            }
            return sum;
        }

        // 回调函数,即当线程异步结束以后调用此方法
        private static void CallBack(IAsyncResult ar)
        {
            AsyncResult AR = ar as AsyncResult;
            Console.WriteLine("异步调用的回调参数为{0}", AR.AsyncState); //获得并输出异步调用的结果
            int s = ((MyDelegate)AR.AsyncDelegate).EndInvoke(ar);
            Console.WriteLine("Sum is: {0}", s);
        }

    }

    // 声明委托
    public delegate int MyDelegate(int fromNum, int toNum);
}