C#异步编程模式IAsyncResult浅析

 


  • C#异步编程模式IAsyncResult是什么呢?我们需要明白C#异步编程模式IAsyncResult什么方面呢?那么本文就向你介绍相关的内容。
  •  

    C#异步编程模式IAsyncResult概述

    IAsyncResult 异步设计模式通过名为 BeginOperationName 和 EndOperationName 的两个方法来实现原同步方法的异步调用,如 FileStream 类提供了 BeginRead 和 EndRead 方法来从文件异步读取字节,它们是 Read 方法的异步版本

    Begin 方法包含同步方法签名中的任何参数,此外还包含另外两个参数:一个AsyncCallback 委托和一个用户定义的状态对象。委托用来调用回调方法,状态对象是用来向回调方法传递状态信息。该方法返回一个实现 IAsyncResult 接口的对象

    End 方法用于结束异步操作并返回结果,因此包含同步方法签名中的 ref 和 out 参数,返回值类型也与同步方法相同。该方法还包括一个 IAsyncResult 参数,用于获取异步操作是否完成的信息,当然在使用时就必须传入对应的 Begin 方法返回的对象实例

    开始异步操作后如果要阻止应用程序,可以直接调用 End 方法,这会阻止应用程序直到异步操作完成后再继续执行。也可以使用 IAsyncResult 的 AsyncWaitHandle 属性,调用其中的WaitOne等方法来阻塞线程。这两种方法的区别不大,只是前者必须一直等待而后者可以设置等待超时

    如果不阻止应用程序,则可以通过轮循 IAsyncResult 的 IsCompleted 状态来判断操作是否完成,或使用 AsyncCallback 委托来结束异步操作。AsyncCallback 委托包含一个 IAsyncResult 的签名,回调方法内部再调用 End 方法来获取操作执行结果

    C#异步编程模式IAsyncResult之IAsyncResult 接口

       
       
    1. public   interface  IAsyncResult  
    2. {  
    3. object  AsyncState {  get ; }  
    4. WaitHandle AsyncWaitHandle {  get ; }  
    5. bool  CompletedSynchronously {  get ; }  
    6. bool  IsCompleted {  get ; }  

    我用一个 AsyncDemo 类作为异步方法的提供者,后面的程序都会调用它。内部很简单,构造函数接收一个字符串作为 name ,Run 方法输出 "My name is " + name ,而异步方法直接用委托的 BeginInvoke 和 EndInvoke 方法实现

       
       
    1. public   class  AsyncDemo  
    2. {  
    3. // Use in asynchronous methods  
    4. private   delegate   string  runDelegate();  
    5.  
    6. private   string  m_Name;  
    7. private  runDelegate m_Delegate;  
    8.  
    9. public  AsyncDemo( string  name)  
    10. {  
    11. m_Name = name;  
    12. m_Delegate =  new  runDelegate(Run);  
    13. }  
    14.  
    15. /**/ /// ﹤summary﹥  
    16. /// Synchronous method  
    17. /// ﹤/summary﹥  
    18. /// ﹤returns﹥﹤/returns﹥  
    19. public   string  Run()  
    20. {  
    21. return   "My name is "  + m_Name;  
    22. }  
    23.  
    24. /**/ /// ﹤summary﹥  
    25. /// Asynchronous begin method  
    26. /// ﹤/summary﹥  
    27. /// ﹤param name="callBack"﹥﹤/param﹥  
    28. /// ﹤param name="stateObject"﹥﹤/param﹥  
    29. /// ﹤returns﹥﹤/returns﹥  
    30. public  IAsyncResult BeginRun(  
    31. AsyncCallback callBack, Object stateObject)  
    32. {  
    33. try  
    34. {  
    35. return  m_Delegate.BeginInvoke(callBack, stateObject);  
    36. }  
    37. catch (Exception e)  
    38. {  
    39. // Hide inside method invoking stack  
    40. throw  e;  
    41. }  
    42. }  
    43.  
    44. /**/ /// ﹤summary﹥  
    45. /// Asynchronous end method  
    46. /// ﹤/summary﹥  
    47. /// ﹤param name="ar"﹥﹤/param﹥  
    48. /// ﹤returns﹥﹤/returns﹥  
    49. public   string  EndRun(IAsyncResult ar)  
    50. {  
    51. if  (ar ==  null )  
    52. throw   new  NullReferenceException(  
    53. "Arggument ar can't be null" );  
    54.  
    55. try  
    56. {  
    57. return  m_Delegate.EndInvoke(ar);  
    58. }  
    59. catch  (Exception e)  
    60. {  
    61. // Hide inside method invoking stack  
    62. throw  e;  
    63. }  
    64. }  

    C#异步编程模式IAsyncResult操作步骤:首先是 Begin 之后直接调用 End 方法,当然中间也可以做其他的操作

       
       
    1. class  AsyncTest  
    2. {  
    3. static   void  Main( string [] args)  
    4. {  
    5. AsyncDemo demo =  new  AsyncDemo( "jiangnii" );  
    6.  
    7. // Execute begin method  
    8. IAsyncResult ar = demo.BeginRun( nullnull );  
    9.  
    10. // You can do other things here  
    11.  
    12. // Use end method to block thread  
    13. // until the operation is complete  
    14. string  demoName = demo.EndRun(ar);  
    15. Console.WriteLine(demoName);  
    16. }  

    也可以用 IAsyncResult 的 AsyncWaitHandle 属性,我在这里设置为1秒超时

       
       
    1. class  AsyncTest  
    2. {  
    3. static   void  Main( string [] args)  
    4. {  
    5. AsyncDemo demo =  new  AsyncDemo( "jiangnii" );  
    6.  
    7. // Execute begin method  
    8. IAsyncResult ar = demo.BeginRun( nullnull );  
    9.  
    10. // You can do other things here  
    11.  
    12. // Use AsyncWaitHandle.WaitOne method to block thread for 1 second at most  
    13. ar.AsyncWaitHandle.WaitOne(1000,  false );  
    14.  
    15. if  (ar.IsCompleted)  
    16. {  
    17. // Still need use end method to get result,  
    18. // but this time it will return immediately   
    19. string  demoName = demo.EndRun(ar);  
    20. Console.WriteLine(demoName);  
    21. }  
    22. else  
    23. {  
    24. Console.WriteLine("Sorry,  
    25. can't  get  demoName, the time  is  over");  
    26. }  
    27. }  

    C#异步编程模式IAsyncResult要注意的还有:不中断的循环,每次循环输出一个 "."

       
       
    1. class  AsyncTest  
    2. {  
    3. static   void  Main( string [] args)  
    4. {  
    5. AsyncDemo demo =  new  AsyncDemo( "jiangnii" );  
    6.  
    7. // Execute begin method  
    8. IAsyncResult ar = demo.BeginRun( nullnull );  
    9.  
    10. Console.Write( "Waiting.." );  
    11. while  (!ar.IsCompleted)  
    12. {  
    13. Console.Write( "." );  
    14. // You can do other things here  
    15. }  
    16. Console.WriteLine();  
    17.  
    18. // Still need use end method to get result,   
    19. //but this time it will return immediately   
    20. string  demoName = demo.EndRun(ar);  
    21. Console.WriteLine(demoName);  
    22. }  
    23. }  

    最后是使用回调方法并加上状态对象,状态对象被作为 IAsyncResult 参数的 AsyncState 属性被传给回调方法。回调方法执行前不能让主线程退出,我这里只是简单的让其休眠了1秒。另一个与之前不同的地方是 AsyncDemo 对象被定义成了类的静态字段,以便回调方法使用

       
       
    1. class  AsyncTest  
    2. {  
    3. static  AsyncDemo demo =  new  AsyncDemo( "jiangnii" );  
    4.  
    5. static   void  Main( string [] args)  
    6. {  
    7. // State object  
    8. bool  state =  false ;  
    9.  
    10. // Execute begin method  
    11. IAsyncResult ar = demo.BeginRun(  
    12. new  AsyncCallback(outPut), state);  
    13.  
    14. // You can do other thins here  
    15.  
    16. // Wait until callback finished  
    17. System.Threading.Thread.Sleep(1000);  
    18. }  
    19.  
    20. // Callback method  
    21. static   void  outPut(IAsyncResult ar)  
    22. {  
    23. bool  state = ( bool )ar.AsyncState;  
    24. string  demoName = demo.EndRun(ar);  
    25.  
    26. if  (state)  
    27. {  
    28. Console.WriteLine(demoName);  
    29. }  
    30. else  
    31. {  
    32. Console.WriteLine(demoName +  ", isn't it?" );  
    33. }  
    34. }  

    C#异步编程模式IAsyncResult的后话:

    对于一个已经实现了 BeginOperationName 和 EndOperationName方法的对象,我们可以直接用上述方式调用,但对于只有同步方法的对象,我们要对其进行异步调用也不需要增加对应的异步方法,而只需定义一个委托并使用其 BeginInvoke 和 EndInvoke 方法就可以了。

    C#异步编程模式IAsyncResult的基本情况就向你介绍到这里,希望对你了解和学习C#异步编程模式IAsyncResult有所帮助。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值