So far, I have discussed about Callback, Multicast delegatesEvents using delegates, and yet another example of events using delegates. In this post, I will take this topic one step forward and show you an example of Asynchronous callbacks using delegates.

Let's say a client calls a method that takes 40 minutes to complete, how do we communicate with the client?

Option 1> Keep showing that busy Cursor for 40 minutes!!!

Option 2> Keep updating the client with appropriate messages, like... "oh yes... we might take another light year to complete, please wait... oh common..... show some patience... do yoga... etc...  etc...."

Option 3> Tell the client that "okay Sir... you are done with your part... go away take a vacation. Whenever I'm done I will let you know"

As you may agree... Option 3 is a more effective way. Not because it gives you enough time to complete your job , but because the client is not just waiting on you. He is gone after giving you the job and may be doing something else in life. HE is FREE... and FREEDOM is good

Before we proceed, let's see what happened to the delegate from my previous post (in ILDASM)...

Take a look in the figure above and notice that just creating the delegate in your code, actually created a class behind the scenes with a few methods called Invoke, BeginInvoke, and EndInvoke!!!!! Pretty smart, right?

<Snippet from MSDN>

Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.

</Snippet from MSDN>

Asynchronous calls has two important parts... BeginInvoke and EndInvoke. Once BeginInvoke is called, EndInvoke can be called anytime. The catch is that EndInvoke is a blocking call. Thus, it would block the calling thread until it is complete. There are several ways in which you could work with BeginInvoke and EndInvoke at tandem. In this post we will take a look at the first way!!

The following code is almost like a husband telling his wife (whom he is dropping in a mall for some shopping!!)...

You know honey, I have a lot of work to do. Why don't you help me up by doing something that you can do pretty well . In the meantime, I will take care of some other stuff. As soon as I am done, I promise I will pick you up.

The good thing with this approach is that the wife (in our case, a new thread) is doing something, while the main thread can continue to do something else. The catch is that, the husband (main thread) must be aware that once its job is done, it will have to wait (blocking call) for his wife (the other thread)!! Just like I do, well... almost always

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; namespace EventAndDelegateDemo
{
//The delegate must have the same signature as the method. In this case,
//we will make it same as TortoiseMethod
public delegate string TortoiseCaller(int seconds, out int threadId); public class TortoiseClass
{
// The method to be executed asynchronously.
public string TortoiseMethod(int seconds, out int threadId)
{
Console.WriteLine("The slow method... executes...on thread {0}", Thread.CurrentThread.ManagedThreadId);
for (int i = ; i < ; i++)
{
Thread.Sleep(seconds / * );
Console.WriteLine("The async task is going on... {0}", Thread.CurrentThread.ManagedThreadId);
}
threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("I worked in my sleep for {0} seconds", seconds.ToString());
}
} //Now, that we are done with the declaration part, let's proceed to
//consume the classes and see it in action
//The algorithm would be very simple...
// 1. Call delegate's BeginInvoke
// 2. Do some work on the main thread
// 3. Call the delegate's EndInvoke
public class TortoiseConsumer
{
public static void Main()
{
//Instantiate a new TortoiseClass
TortoiseClass tc = new TortoiseClass();
//Let's create the delegate now
TortoiseCaller caller = new TortoiseCaller(tc.TortoiseMethod);
//The asynchronous method puts the thread id here
int threadId;
//Make the async call. Notice that this thread continues to run after making this call
Console.WriteLine("Before making the Async call... Thread ID = {0}", Thread.CurrentThread.ManagedThreadId);
IAsyncResult result = caller.BeginInvoke(, out threadId, null, null);
Console.WriteLine("After making the Async call... Thread ID = {0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Perform more work as the other thread works...");
for (int i = ; i > ; i--)
{
Thread.Sleep();
Console.WriteLine("{0}...", i);
}
Console.WriteLine("Waiting for the async call to return now...");
//Notice that this call will be a blocking call
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("The call got executed on thread {0}", threadId);
Console.WriteLine("The value returned was - {0}", returnValue);
}
}
}

I will discuss about more ways of doing asynchronous programming in some of my next posts.

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

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

  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 7 (Asynchronous Callback - Way 4)

    This is the final part of the series that started with... Callback and Multicast delegatesOne more E ...

  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. 微信中关闭网页输入内容时的安全提示 [干掉 “防盗号或诈骗,请不要输入QQ密码”]

    未设置之前: 需要把域名加入白名单 设置方法:微信公共平台后台-->公众号设置--->功能设置--->填写业务域名即可.

  2. C#中二进制和流之间的各种相互转换

    一. 二进制转换成图片间的转换 1 2 3 4 5 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Image img = Im ...

  3. 自定义shareSDK的验证码短信内容

    应用中使用了shareSDK来做第三方登录和短信验证码的接收,但是想将短信内容修改为自己想要的内容 官方文档中并未详细提及:无GUI接口调用 默认的短信内容为: 如果只是要修改括号中的抬头,只需按照此 ...

  4. 在C++中调用DLL中的函数(2)

    本文转自:http://blog.sina.com.cn/s/blog_53004b4901009h3b.html 应用程序使用DLL可以采用两种方式: 一种是隐式链接,另一种是显式链接.在使用DLL ...

  5. android设置主mic/副mic录音

    //添加MIC设置参数 /hal/audio_extn/audio_extn.c @@ -75,6 +75,7 @@ struct audio_extn_module { bool ras_enabl ...

  6. VMware Ubuntu NAT 不能上网

    在VMware中配置NAT,控制面板->网络和Internet->网络连接,设置对应的VMware网卡为DHCP. ubuntu虚拟机中配置网卡为DHCP.获取不到ip. 参考链接: ht ...

  7. CI框架 -- 附属类

    有些时候,你可能想在你的控制器之外新建一些类,但同时又希望 这些类还能访问 CodeIgniter 的资源 任何在你的控制器方法中初始化的类都可以简单的通过 get_instance() 函数来访问 ...

  8. 如何去掉jQWidgets中TreeGrid和Grid右下角的链接

    关于如何去掉这个水印,这是官方的说法. 更新了jQWidgets版本,发现在使用过程中发现每次渲染完TreeGrid和Grid后会在表格右下角出现一个www.jqwidgets.com的span标签. ...

  9. php 一维数组去重

    $input = array("a" => "green", "red", "b" => "gre ...

  10. Caffe 学习:Eltwise层

    Eltwise层的操作有三个: 1. PROD(product):按元素乘积 2. SUM:按元素求和(默认操作) 3. MAX:保存元素大者