博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
异步使用委托delegate --- BeginInvoke和EndInvoke方法
阅读量:4632 次
发布时间:2019-06-09

本文共 1464 字,大约阅读时间需要 4 分钟。

当我们定义一个委托的时候,一般语言运行时会自动帮委托定义BeginInvoke 和 EndInvoke两个方法,这两个方法的作用是可以异步调用委托。

方法BeginInvoke有两个参数:

  • AsyncCallBack:回调函数,是一个委托,没有返回值,可以传一个参数,参数类型是object;
  • object AsyncState :回调函数的参数。

BeginInvoke的返回值是IAsyncResult,

方法EndInvoke需要的参数是BeginInvoke的返回值IAsyncResult.

举例如下:

class AsyncStateTest    {        private delegate void DelegateTest();        public static void TestAsyncState()        {            DelegateTest delegateTest = new DelegateTest(delegateImpl);            Console.WriteLine("Main method begin delegateTest");            IAsyncResult asyncResult = delegateTest.BeginInvoke(new AsyncCallback(CallBack), "I am AsyncState(*_*)");            //delegateTest.EndInvoke(asyncResult);            Console.WriteLine("Main method end delegateTest");            delegateTest.EndInvoke(asyncResult);            Console.WriteLine("Main method continue");        }        private static void CallBack(IAsyncResult asyncResult)        {            object state = asyncResult.AsyncState;            Console.WriteLine(state.ToString());        }        private static void delegateImpl()        {            Console.WriteLine("I am DelegateTest Impl");        }    }

运行结果:

Main method begin delegateTestMain method end delegateTestI am DelegateTest ImplMain method continueI am AsyncState(*_*)

可以看到,主线程的输出先于委托方法的输出,证明该方法被异步执行了。另外EndInvoke方法的作用是阻塞线程(调用委托的主线程),使之等到委托的方法执行完毕(但是不会等到委托的回调函数执行完毕),上面的代码换一下EndInvoke方法的位置可以看到结果。

转载于:https://www.cnblogs.com/heisehenbai/p/10100278.html

你可能感兴趣的文章
本地建立svn管理项目
查看>>
SPSS单一样本的T检验
查看>>
记一次代码错误的排查
查看>>
In c++ access control works on per-class basis not on per-object basis.
查看>>
关于c++预处理器错误(待续)
查看>>
清空进程间通信消息队列
查看>>
Marmoset Toolbag中的角色布光技巧 by Joe”EarthQuake”Wilson
查看>>
http://forum.jquery.com/topic/file-upload-ajaxsubmit-sends-response-to-wrong-window-in-ie
查看>>
php的文件下载
查看>>
easyui的增删改
查看>>
Sql Server数据库性能优化之索引
查看>>
【Android UI】 Shape详… 分类: ...
查看>>
MFC 屏幕截图(libjpeg bmp转jpg)
查看>>
jQuery中 wrap() wrapAll() 与 wrapInner()的区别
查看>>
第二阶段冲刺第二天
查看>>
JS字符串转换成json对象。。。。
查看>>
yaml语法三大规则
查看>>
【HANA系列】SAP HANA的特点总结
查看>>
修改选中文字的背景色
查看>>
【CodeForces - 546C】Soldier and Cards (vector或队列)
查看>>