异步委托调用

来源:互联网 发布:leslie矩阵模型 编辑:程序博客网 时间:2024/06/08 02:16
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)
        {
            #region 调用无参数,无返回值的委托
            MyDelegate1 md = new MyDelegate1(T1);
            
            // 正常调用
            //md();
            //md.Invoke();
            IAsyncResult result = md.BeginInvoke(null, null); // 直接开始异步调用委托
            md.EndInvoke(result); // 保证异步委托调用结束后开始执行下面的代码 
            Console.WriteLine("OK");
            //Console.ReadKey();
            #endregion


            #region  带参数无返回值的委托
            MyDelegate2 md2 = new MyDelegate2(T2);
            IAsyncResult result2 = md2.BeginInvoke("zxh", 18, null, null); //开始异步调用
            md2.EndInvoke(result2);
            Console.WriteLine("OK");
            //Console.ReadKey();
            #endregion


            #region 异步调用带参数,带返回值的委托,需要使用异步调用委托的回调函数
            GetSumDelegate gsd = new GetSumDelegate(T3);
            //gsd.BeginInvoke(1, 10, new AsyncCallback(ar => 
            //{ 
            
            //}), "ymh");
            gsd.BeginInvoke(1, 10, new AsyncCallback(FuncCallBack), "hxq");




            Console.WriteLine("异步委托开始调用了!");
            Console.ReadKey();


            #endregion
        }


        static void FuncCallBack(IAsyncResult ar)
        {
            // 回调函数中首先先把IAsyncResult类型转化为ASyncResult类型,方便后面的使用
            AsyncResult result = ar as AsyncResult;
            // 获取用户在进行异步委托调用传递过来的最后一个参数
            Console.WriteLine("最后一个参数:" + result.AsyncState.ToString());
            // 获取当前被调用的异步委托对象
            GetSumDelegate currentDelegate = result.AsyncDelegate as GetSumDelegate;
            // 获取委托异步调用后的返回值
            int sum = currentDelegate.EndInvoke(ar);
            Console.WriteLine("最后的结果是:" + sum);
        }


        static int T3(int f, int t)
        {
            int sum = 0;
            for (int i = f; i <= t; i++)
            {
                sum += i;
                Thread.Sleep(500);
            }
            return sum;
        }


        static void T1()
        {
            Console.WriteLine("T1");
            Thread.Sleep(1000);
            Console.WriteLine("T1");     
        }


        static void T2(string s1, int n1)
        {
            Console.WriteLine("s1={0}", s1);
            Thread.Sleep(1000);
            Console.WriteLine("n1={0}", n1);
        }


    }


    public delegate int GetSumDelegate(int from, int to);


    public delegate void MyDelegate2(string s1, int n1);


    public delegate void MyDelegate1();
}
0 0
原创粉丝点击