This is the final part of the series that started with...

Callback and Multicast delegates
One more Event
Asynchronous Callback - Way 1 - BeginInvoke > EndInvoke
Asynchronous Callback - Way 2 - BeginInvoke > AsyncWaitHandle.WaitOne(x) > EndInvoke > AsynWaitHandle.Close()
Asynchronous Callback - Way 3 - BeginInvoke > Poll for result's IsCompleted > EndInvoke

In this scenario, if we go with the husband-wife-kiddo analogy, I will need to introduce another guy! No no no... please don't misunderstand me... he is the just the driver 

So, now the husband drops his wife at the mall. And instead of coming back to pick her up, he simply says... honey, I am going to the office. When you are done shopping,  call the driver (+91-97415-xxxxx) and he would take you home.

NOTE >

  • As soon as the main thread calls the asynchronous method, his part is done
  • The callback method is executed on the ThreadPool thread
  • The call to BeginInvoke (so far... it has been something like... caller.BeginInvoke(25, out threadId, null, null);) would now have the 3rd parameter as an AsyncCallback which contains the callback method name.
  • The 4th parameter takes an object which your callback method might like to use
  • The ThreadPool threads are background threads. This means that they won't keep the application running in case the main thread ends. Thus, the main thread has to be alive for long enough to ensure that the background threads are done processing.

Let's take a look at the code (and read the comments to get a better understanding!).

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Diagnostics;
  7. using System.Runtime.Remoting.Messaging;
  8.  
  9. namespace EventAndDelegateDemo
  10. {
  11. //The delegate must have the same signature as the method. In this case,
  12. //we will make it same as TortoiseMethod
  13. public delegate string TortoiseCaller(int seconds, out int threadID);
  14.  
  15. public class TortoiseClass
  16. {
  17. // The method to be executed asynchronously.
  18. public string TortoiseMethod(int seconds, out int threadID)
  19. {
  20. threadID = Thread.CurrentThread.ManagedThreadId;
  21. Console.WriteLine("The slow method... executes...on thread {0}", Thread.CurrentThread.ManagedThreadId);
  22. for (int i = ; i < ; i++)
  23. {
  24. Thread.Sleep(seconds / * );
  25. Console.WriteLine("The async task is going on thread # {0}", Thread.CurrentThread.ManagedThreadId);
  26. }
  27. return String.Format("I worked in my sleep for {0} seconds", seconds.ToString());
  28. }
  29. }
  30.  
  31. //Now, that we are done with the declaration part, let's proceed to
  32. //consume the classes and see it in action
  33. //The algorithm would be very simple...
  34. // 1. Call delegate's BeginInvoke and pass the callback method's name
  35. // 2. Do some work on the main thread
  36. // 3. Your callback method is called when the processing completes.
  37. // 4. Retrieve the delegate and call EndInvoke which won't be a blocking call this time!
  38. public class TortoiseConsumer
  39. {
  40. static void Main()
  41. {
  42. //Instantiate a new TortoiseClass
  43. TortoiseClass tc = new TortoiseClass();
  44. //Let's create the delegate now
  45. TortoiseCaller caller = new TortoiseCaller(tc.TortoiseMethod);
  46.  
  47. //This is a dummy variable since this thread is not supposed to handle the callback anyways!!!
  48. int dummy = ;
  49. //Start the asynchronous call with the following parameters...
  50. //Parameter 1 = 30 > In my example the tortoise class will now do something for 30 seconds
  51. //Parameter 2 = Dummy variable, just to get the output of the threadID
  52. //Parameter 3 = new AsyncCallback(CallbackMethod) > This is the method which would be called once the async task is over
  53. //Parameter 4 = Object > This is a string which would display the information about the async call
  54. IAsyncResult result = caller.BeginInvoke(, out dummy, new AsyncCallback(CallThisMethodWhenDone),
  55. "The call executed on thread {0}, with return value \"{1}\".");
  56.  
  57. Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId);
  58.  
  59. //The callback method will use a thread from the ThreadPool.
  60. //But the threadpool threads are background threads. This implies that if you comment the line below
  61. //you would notice that the callback method is never called, since the background threads can't stop the main
  62. //program to terminate!
  63. Thread.Sleep();
  64. Console.WriteLine("The main thread ends. Change the value 3000 in code to 40000 and see the result");
  65. }
  66.  
  67. //The signature for the call back method must be same System.IAsyncResult delegate.
  68. static void CallThisMethodWhenDone(System.IAsyncResult ar)
  69. {
  70. //To retrieve the delegate we will cast the IAsyncResult to AsyncResult and get the caller
  71. AsyncResult result = (AsyncResult)ar;
  72. TortoiseCaller caller = (TortoiseCaller)result.AsyncDelegate;
  73.  
  74. //Get the object (in our case it is just a format string) that was passed while calling BeginInvoke!
  75. string formattedString = (string)ar.AsyncState;
  76.  
  77. // Define a variable to receive the value of the out parameter.
  78. // If the parameter were ref rather than out then it would have to
  79. // be a class-level field so it could also be passed to BeginInvoke.
  80. //The following variable would take the Thread ID
  81. int threadId = ;
  82.  
  83. //At this point, the threadID won't be a dummy variable as it was in the Main method
  84. //We are passing threadID to get the output from the TortoiseMethod
  85. string returnValue = caller.EndInvoke(out threadId, ar);
  86.  
  87. //Use the format string to format the output message.
  88. Console.WriteLine(formattedString, threadId, returnValue);
  89. }
  90. }
  91. }

There will be more on Delegates and Asynchronous programming going forward.

转:http://www.dotnetscraps.com/dotnetscraps/post/Explaining-Delegates-in-C-Part-7-(Asynchronous-Callback-Way-4).aspx

Explaining Delegates in C# - Part 7 (Asynchronous Callback - Way 4)的更多相关文章

  1. Explaining Delegates in C# - Part 6 (Asynchronous Callback - Way 3)

    By now, I have shown the following usages of delegates... Callback and Multicast delegatesEventsOne ...

  2. Explaining Delegates in C# - Part 4 (Asynchronous Callback - Way 1)

    So far, I have discussed about Callback, Multicast delegates, Events using delegates, and yet anothe ...

  3. Explaining Delegates in C# - Part 5 (Asynchronous Callback - Way 2)

    In this part of making asynchronous programming with delegates, we will talk about a different way, ...

  4. Synchronous/Asynchronous:任务的同步异步,以及asynchronous callback异步回调

    两个线程执行任务有同步和异步之分,看了Quora上的一些问答有了更深的认识. When you execute something synchronously, you wait for it to ...

  5. Explaining Delegates in C# - Part 1 (Callback and Multicast delegates)

    I hear a lot of confusion around Delegates in C#, and today I am going to give it shot of explaining ...

  6. Explaining Delegates in C# - Part 2 (Events 1)

    In my previous post, I spoke about a few very basic and simple reasons of using delegates - primaril ...

  7. Explaining Delegates in C# - Part 3 (Events 2)

    I was thinking that the previous post on Events and Delegates was quite self-explanatory. A couple o ...

  8. [TypeScript] Simplify asynchronous callback functions using async/await

    Learn how to write a promise based delay function and then use it in async await to see how much it ...

  9. Delegates and Events

    People often find it difficult to see the difference between events and delegates. C# doesn't help m ...

随机推荐

  1. VMware Fusion 5 正式版序列号

    HV4KJ-2X10K-VZ768-DRAGP-8CU2F MY63N-D0HE2-0ZXC1-HV954-937JL

  2. Ubuntu下Ruby的下载和编译源码安装

    1.Ruby的下载 Ruby可以在Ruby 官网上下载,如果想获取更多的Ruby版本,可以到淘宝镜像网站下载. 2.Ruby的编译源码安装 解压 首先把下载下来的源码压缩包解压到自己指定的目录 编译安 ...

  3. 珍藏40个android应用源码分享

    1.高仿京东商城源码http://www.apkbus.com/android-115203-1-1.html 2.抽屉demohttp://www.apkbus.com/android-115205 ...

  4. e785. 监听JList中项的变动

    When the set of items in a list component is changed, a list data event is fired. // Create a list t ...

  5. Microsoft Jet 数据库引擎打不开文件,它已经被别的用户以独占方式打开,或没有查看数据的权限。

    System.Data.OleDb.OleDbException (0x80004005): Microsoft Jet 数据库引擎打不开文件'D:\wwwroot\gonghouxie\wwwroo ...

  6. XP远程桌面连接2008提示:远程计算机需要网络级别身份验证,而您的计算机不支持该验证

    原文链接:http://kong62.blog.163.com/blog/static/1760923052011319113044653/ 解决办法: 修改注册表2个地方 开始-运行-regedit ...

  7. Yii2 响应部分 response

    当应用完成处理一个请求后, 会生成一个yii\web\Response响应对象并发送给终端用户 响应对象包含的信息有HTTP状态码,HTTP头和主体内容等, 网页应用开发的最终目的本质上就是根据不同的 ...

  8. ubuntu安装mongo数据库

    安装mongo数据库,在shell下输入 sudo apt-get install mongodb 如果需要在Python中使用mongo数据库,还需要额外安装Python封装库 pip instal ...

  9. 带有Header的SOAP 请求

    package demo.test; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import org.t ...

  10. Macbook pro安装MacOS系统

    在app store 下载系统sierra; 打开磁盘工具,选择优盘,抹掉: 日志式,GUID分区: http://www.cnblogs.com/xiaobo-Linux/ 终端输入命令, sudo ...