首页 > 学院 > 开发设计 > 正文

C#委托学习之回调

2019-11-08 02:00:31
字体:
来源:转载
供稿:网友

    委托:

    在c#中定义为:委托就像一个函数的指针,在程序运行时可以使用它们来调用不同的函数。

    我的理解就是一个方法,但是需要传入的参数类型与普通参数不同,需要传入另一个方法作为参数。

  委托的使用:

    首先定义一个委托类:public delegate int MethodDel();

    然后实例化一个委托:public MethodDel addMethod = new MethodDel(Add);,其中Add();方法的返回值与参数必须与定义的委托类的返回值和参数相同。

    使用时可以添加委托链:addMethod += Add2;同理也可以进行减等操作。

委托的调用:

    委托的调用分为同步调用、异步调用和异步回调。

    同步调用:即使用Invoke();方法。同步调用又称阻塞调用,会阻塞当前线程。

    异步调用:一步调用不会阻塞线程,而是把线程放到线程池中,程序会继续执行。通过BeginInvoke();EndInvoke();来实现。

但是如果运行到EndInvoke();时,调用没有执行完毕,依然会阻塞线程。

    异步回调:当调用结束时会自动调用回到函数,解决了为等待调用结果,而让线程依旧被阻塞的局面。

测试代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;using System.Collections;using System.Runtime.Remoting.Messaging;namespace StudyTest{    class PRogram    {        public delegate int MethodDel();        public static MethodDel addMethod = new MethodDel(Add);        static void Main(string[] args)        {            Console.ReadKey();            addMethod.Invoke();            Console.WriteLine("同步调用完成");            Console.ReadKey();            IAsyncResult resule = addMethod.BeginInvoke(null, null);            Console.WriteLine("做别的事情");            Console.ReadKey();//代表做别的事情,再次停顿5秒以上            addMethod.EndInvoke(resule);            Console.WriteLine("异步调用完成");            Console.ReadKey();            IAsyncResult resulet = addMethod.BeginInvoke(new AsyncCallback(回调函数), "AsycState:OK");            Console.WriteLine("做别的事情");            Console.ReadKey();        }        public static int Add()        {            Thread.Sleep(5000);//代表正在调用,停止5秒            return 3;        }        public static void 回调函数(IAsyncResult result)        {            addMethod= (MethodDel)((AsyncResult)result).AsyncDelegate;            Console.WriteLine(addMethod.EndInvoke(result));            Console.WriteLine(result.AsyncState);        }    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表