举例说明Control.Invoke, Control.BeginInvoke, DelegateBeginInvoke
来源:互联网 发布:比较两组数据差异 编辑:程序博客网 时间:2024/06/10 14:22
Control.Invoke, Control.BeginInvoke, DelegateBeginInvoke是很常用的调用委托方法。
它们各有区别,以下代码通过举例说明这三者之间的不同点:
#region 公用方法 //定义委托 private delegate string InvokeDelegate(string str1,string str2); //处理函数 private string InvokeMethod(string str1, string str2) { DateTime d1 = DateTime.Now; //停顿5秒 while (1 == 1) { if (DateTime.Now.Subtract(d1).TotalSeconds >= 5) { break; } } //返回值 return "OK"; } //异步委托,执行完处理函数后,回调处理结果 private void CallBackHandler(IAsyncResult iar) { if (iar.IsCompleted) { AsyncResult ar = iar as AsyncResult; string sResult = ((InvokeDelegate)ar.AsyncDelegate).EndInvoke(iar); MessageBox.Show(sResult); } } #endregion //1.控件的Invoke,在UI线程上执行。 private void btnCtrlInvoke_Click(object sender, EventArgs e) { this.Invoke(new InvokeDelegate(InvokeMethod),"",""); //需等待Invoke执行完处理函数后,才执行下一句 MessageBox.Show("Finished"); } //2.控件的BeginInvoke,在UI线程上异步执行 private void btnCtrlBeginInvoke_Click(object sender, EventArgs e) { this.BeginInvoke (new InvokeDelegate(InvokeMethod),"",""); //不需等待执行完处理函数,即执行下一句。但因为是在UI线程,所以涉及到UI操作的,都需等UI空闲后,才可刷新UI MessageBox.Show("Finished"); } //3.委托式的BeginInvoke,使用另一线程执行。 private void btnDelegateBeginInvoke_Click(object sender, EventArgs e) { InvokeDelegate xDelegate = new InvokeDelegate(this.InvokeMethod); AsyncCallback xCallBack=new AsyncCallback(CallBackHandler ); xDelegate.BeginInvoke("", "", xCallBack, ""); //不需等待执行完处理函数,即执行下一句。因为是使用另一线程,这时UI不会假死。处理函数完成后,使用回调xCallBack来反馈结果到UI。 MessageBox.Show("Finished"); }
- 举例说明Control.Invoke, Control.BeginInvoke, DelegateBeginInvoke
- Control.Invoke&Control.BeginInvoke
- Control.INvoke 和 Control.BeginInvoke
- Control .BeginInvoke 与Invoke
- control中的invoke、begininvoke
- control 的invoke 和begininvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- Control的Invoke和BeginInvoke
- 这个夏天我们留下的
- LPVOID
- 用js操作table、tr、td 「字体样式及TD背景图片」
- HRESULT --转自baidu百科
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- 举例说明Control.Invoke, Control.BeginInvoke, DelegateBeginInvoke
- python 全排列
- 创建和使用Android library工程
- 拜读大牛Ulrich Drepper大作之How To Write Shared Libraries
- ORA-12516: TNS: 监听程序找不到符合协议堆栈要求的可用处理程错
- Problems with opening CHM Help files from Network or Internet
- 免费的Android UI库及组件推荐
- ORA-12516: TNS: 监听程序找不到符合协议堆栈要求的可用处理程
- MSXML