AsyncCallback BeginInvode endinvode 异步调用

下面是搜藏的代码:

  1. //首先准备好,要进行C#异步调用的方法(能C#异步调用的,最好不多线程)  
  2. private string MethodName(int Num, out int Num2)  
  3. {  
  4.  Num2 = Num;  
  5.  return "HelloWorld";  
  6. }   
  7.  
  8. //程序终点  
  9. //C#异步调用完成时,执行的方法(回调方法),  
  10. //此方法只能有IAsyncResult一个参数,但是该参数几乎万能,可以传递object  
  11. private void CallBackMethod(IAsyncResult ar)  
  12. {  
  13.  //从C#异步调用状态ar.AsyncState中,获取委托对象  
  14.  DelegateName dn = (DelegateName)ar.AsyncState;  
  15.  //输出参数  
  16.  int i;   
  17.  
  18.  //一定要EndInvoke,否则你的下场很惨  
  19.  string r = dn.EndInvoke(out i, ar);  
  20.  MessageBox.Show("C#异步调用完成喽!i的值是" i.ToString() ",r的值是" r);  
  21. }   
  22.  
  23. //定义与方法同签名的委托  
  24. private delegate string DelegateName(int Num, out int Num2);   
  25.  
  26. //程序入口  
  27. private void Run()  
  28. {  
  29.  //实例化委托并初赋值  
  30.  DelegateName dn = new DelegateName(MethodName);  
  31.  //输出参数  
  32.  int i;  
  33.  //实例化回调方法  
  34.  //把AsyncCallback看成Delegate你就懂了,  
  35. //实际上AsyncCallback是一种特殊的Delegate,就像Event似的  
  36.  AsyncCallback acb = new AsyncCallback(CallBackMethod);  
  37.  //C#异步调用开始  
  38.  //如果参数acb换成null则表示没有回调方法  
  39.  //最后一个参数dn的地方,可以换成任意对象,  
  40. //该对象可以被回调方法从参数中获取出来,写成null也可以。  
  41. //参数dn相当于该线程的ID,如果有多个C#异步调用线程,  
  42. //可以都是null,但是绝对不能一样,不能是同一个object,否则异常  
  43.  IAsyncResult iar = dn.BeginInvoke(1, out i, acb, dn);  
  44.  //去做别的事  
  45.  //…………  
  46. }   
  47.  
  48. //最后的结果应该是:i=1,r="HelloWorld"  

另外,如果可以,定义委托的时候可以选择不用过多的修饰:

  1. /// ﹤summary﹥  
  2. /// 定义委托  
  3. /// ﹤/summary﹥  
  4. /// ﹤returns﹥﹤/returns﹥  
  5. public delegate bool Asyncdelegate();   
  6.  
  7. /// ﹤summary﹥  
  8. /// Callback method must have the same signature as the  
  9. /// AsyncCallback delegate  
  10. /// ﹤/summary﹥  
  11. /// ﹤param name="ar"﹥﹤/param﹥  
  12. private void CallbackMethod(IAsyncResult ar)  
  13. {  
  14. // Retrieve the delegate.  
  15. Asyncdelegate dlgt = (Asyncdelegate)ar.AsyncState;   
  16.  
  17. // Call EndInvoke to retrieve the results.  
  18. dlgt.EndInvoke(ar);  
  19. }  

其他方法中调用:

  1. //C#异步调用执行  
  2. //指定委托方法  
  3. Asyncdelegate isgt = new Asyncdelegate(icpInfo.Insert);  
  4. IAsyncResult ar = isgt.BeginInvoke(  
  5. new AsyncCallback(CallbackMethod), isgt); 

posted on 2016-03-17 23:01  song2013  阅读(321)  评论(0编辑  收藏  举报

导航