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. 【转】为什么说 Java 程序员必须掌握 Spring Boot ?

    Spring Boot 2.0 的推出又激起了一阵学习 Spring Boot 热,那么, Spring Boot 诞生的背景是什么?Spring 企业又是基于什么样的考虑创建 Spring Boot ...

  2. SQLITE WITH ENTITY FRAMEWORK CODE FIRST AND MIGRATION

    Last month I’ve a chance to develop an app using Sqlite and Entity Framework Code First. Before I st ...

  3. http://www.gasi.ch/blog/inside-deep-zoom-2/

    Inside Deep Zoom – Part II: Mathematical Analysis Welcome to part two of Inside Deep Zoom. In part o ...

  4. Axiom3D:Ogre公告板集与合并批次

    在上文中,我们把Ogre里的网格分解成点线面后,我们要完成一个新的功能,在点上突出显示. 得到顶点位置后,这个功能也就是一个很简单的事,最开始是每个顶点添加一个子节点,节点上添加一个圆点. forea ...

  5. elasticsearch系列三:索引详解(分词器、文档管理、路由详解(集群))

    一.分词器 1. 认识分词器  1.1 Analyzer   分析器 在ES中一个Analyzer 由下面三种组件组合而成: character filter :字符过滤器,对文本进行字符过滤处理,如 ...

  6. Python property,属性

    參考资料 http://www.ibm.com/developerworks/library/os-pythondescriptors/ 顾名思义,property用于生成一个属性.通过操作这个属性. ...

  7. jQuery 文件上传插件:uploadify、swfupload

    jQuery 文件上传插件: uploadify.swfupload

  8. CocoaPods:说点关于它的

    CocoaPods安装和使用教程 安装及使用方法,这里有现成的,很细致,不再赘述(发音:zhuìshù,敲半天ao'shu,找不到这个词 =.=)   记录一下遇到的问题 1.CocoaPods 版本 ...

  9. iOS:根据系统类型加载不同的xib

    1.将 xib 文件名手动更改为 xxx~iphone.xib  和 xxx~ipad.xib 2.初始化时使用 [[xxx alloc] init] 即可,系统会自动判断系统类型并加载对应的 xib ...

  10. CSDN极客头条使用指南

    CSDN极客头条使用指南 今天给大家介绍一下CSDN博客最新推出的这个栏目--CSDN极客头条. 极客头条是什么 极客头条大家分享优质IT资源的聚集地. 大家不仅能够分享CSDN的文章,更能够将其它社 ...