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. SpringMVC深度探险(四) —— SpringMVC核心配置文件详解

    在上一篇文章中,我们从DispatcherServlet谈起,最终为读者详细分析了SpringMVC的初始化主线的全部过程.整个初始化主线的研究,其实始终围绕着DispatcherServlet.We ...

  2. JavaScript世界的一等公民—— 函数

    简介 在很多传统语言(C/C++/Java/C#等)中,函数都是作为一个二等公民存在,你只能用语言的关键字声明一个函数然后调用它,如果需要把函数作为参数传给另一个函数,或是赋值给一个本地变量,又或是作 ...

  3. Oracle 11g 数据库 shutdown 后立即执行 startup mount 报错的解决办法

    最新文章:Virson's Blog 今天在配置Goldengate时Capture进程提示未开启归档日志,然后立即用sys用户登录orcl数据库,然后执行了“shutdown immediate”命 ...

  4. export Jar from eclipse (总结)

    sourceforge 的源码网址 :https://sourceforge.net/projects/fjep/files/fatjar/ <span style="margin:0 ...

  5. 利用altium怎么生成PDF及怎么1:1打印文档

    画完板子之后,还要生成原理图PDF文档,供其他设计人员参考和指正. 上图红框标注的两个地方,分别用于打印预览设置和生成原理图PDF.那么若是生成原理图PDF文档,则选择smart PDF即可. 点击s ...

  6. (笔记)Linux下的CGI和BOA使用期间遇到的问题汇总

    前段时间在做C/S模式下的视频监控,这段时间是B/S模式下的.期间遇到了不少问题,有些问题一卡就是几天,有些问题的解决办法在办法在网上也不是很好找,所以还有些问题虽然得到了临时解决,但是其原理现在我本 ...

  7. Java如何以短格式显示月份?

    在Java中,如何显示短格式的月份名称? 使用DateFormatSymbols().DateFormatSymbols类的getShortMonths()方法,本示例显示了几个月的简写名称. pac ...

  8. lua----------------使用VS2015搭建lua开发环境的一些侥幸成功经验,

    所以本篇博文介绍在Windows平台下,使用VS2015搭建lua开发环境的一些侥幸成功经验,安装过程参考网上教程,安装过程如下(参考http://www.byjth.com/lua/33.html) ...

  9. DOS批处理基础

    1.  echo 和 @ 回显命令 @                   #表示不显示@后面的命令 echo off               #从下一行开始关闭回显 @echo off      ...

  10. [原创]Allegro 导入DXF文件,保留布好的线路信息

    最近智能钥匙产品开发过程中,由于结构装配尺寸的偏差,需要对电路PCB外框OUTLINE进行缩小调整,并且USB插座定位孔改变. Allegro软件在线性绘制方面是有严重缺陷的,想绘制一个异形的板框比较 ...