委托的 同步,异步,异步回调

 

 下面来讨论 异步回调函数

 

1         //回调函数:是异步委托方法执行完成之后,再来调 回调函数。
2         public static void MyAsyncCallback(IAsyncResult ar)
3         {
  #region 当这样调用 时delFunc.BeginInvoke(5, 6, MyAsyncCallback, "123");
            //123是参数

           //1、拿到异步委托执行的结果
            AsyncResult result = (AsyncResult)ar;

            var del1 = (Func<int, int, string>)result.AsyncDelegate;//找到委托
            string returnValue = del1.EndInvoke(result);

            Console.WriteLine("返回值是:" + returnValue);

           //2、拿到给回调函数的参数。
            Console.WriteLine("传给异步回调函数的参数:" + result.AsyncState);

            Console.WriteLine("回调函数的线程 的id是:" + Thread.CurrentThread.ManagedThreadId);//这里的id是委托线程的id
            #endregion 
View Code
 
1  #region 把委托通过参数传过来  delFunc.BeginInvoke(5, 6, MyAsyncCallback, delFunc);
2             //delFunc是委托
3 
4             // //ar.AsyncState 获取用户定义的对象, 就是最后的参数,这里是delFunc
5 
6             var del = (Func<int, int, string>)ar.AsyncState;
7             //找到委托了,,就可以找异步委托执行完的 返回值了
8             string str = del.EndInvoke(ar);
9             #endregion 
View Code
        }

 

 

 

posted @ 2016-08-25 09:44  南潇湘  阅读(208)  评论(0编辑  收藏  举报