C#中的异步调用及异步设计模式(二)——基于 IAsyncResult 的异步设计模式

时间:2023-03-09 22:56:39
C#中的异步调用及异步设计模式(二)——基于 IAsyncResult 的异步设计模式

三、基于 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 方法来获取操作执行结果

  1. public class AsyncDemo
  2. {
  3. // Use in asynchronous methods
  4. private delegate string runDelegate();
  5. private string m_Name;
  6. private runDelegate m_Delegate;
  7. public AsyncDemo(string name)
  8. {
  9. m_Name = name;
  10. m_Delegate = new runDelegate(Run);
  11. }
  12. public string Run()
  13. {
  14. return "My name is " + m_Name;
  15. }
  16. public IAsyncResult BeginRun(AsyncCallback callBack, Object stateObject)
  17. {
  18. try
  19. {
  20. return m_Delegate.BeginInvoke(callBack, stateObject);
  21. }
  22. catch (Exception e)
  23. {
  24. // Hide inside method invoking stack
  25. throw e;
  26. }
  27. }
  28. public string EndRun(IAsyncResult ar)
  29. {
  30. if (ar == null)
  31. throw new NullReferenceException("Arggument ar can't be null");
  32. try
  33. {
  34. return m_Delegate.EndInvoke(ar);
  35. }
  36. catch (Exception e)
  37. {
  38. // Hide inside method invoking stack
  39. throw e;
  40. }
  41. }
  42. }

首先是 Begin 之后直接调用 End 方法,当然中间也可以做其他的操作

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

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

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

不中断的轮循,每次循环输出一个 "."

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

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

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

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

四、基于事件的异步模式(设计层面)

待续...