Explaining Delegates in C# - Part 4 (Asynchronous Callback - Way 1)
So far, I have discussed about Callback, Multicast delegates, Events 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.
Explaining Delegates in C# - Part 4 (Asynchronous Callback - Way 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 ...
- 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 ...
- 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, ...
- Synchronous/Asynchronous:任务的同步异步,以及asynchronous callback异步回调
两个线程执行任务有同步和异步之分,看了Quora上的一些问答有了更深的认识. When you execute something synchronously, you wait for it to ...
- 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 ...
- 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 ...
- 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 ...
- [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 ...
- Delegates and Events
People often find it difficult to see the difference between events and delegates. C# doesn't help m ...
随机推荐
- JS DOM操作思维导图
- R语言-连接MySQL数据库方法
版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] R语言连接数据库常用的方法有2种: 1.使用R数据库接口 连接MySQL,使用RMySQL包,使用前RMySQL包要先安 ...
- Qt的一些鲜为人知但是非常有用的小功能
1. Q_GADGET:不需要从QObject继承就可以使用Qt的Meta Object功能 2. Q_ENUMS:对枚举对象进行反射(reflection) 3. Q_SIGNAL:不需要sig ...
- 自然语言交流系统 phxnet团队 创新实训 项目博客 (十)
关于本项目中使用到的庖丁分词的总结: Paoding 详细介绍 庖丁中文分词库是一个使用Java开发的,可结合到Lucene应用中的,为互联网.企业内部网使用的中文搜索引擎分词组件.Paodi ...
- 启动另一个app
(一) 通过包名.类名 开发有时需要在一个应用中启动另一个应用,比如Launcher加载所有的已安装的程序的列表,当点击图标时可以启动另一个应用.一般我们知道了另一个应用的包名和MainActivit ...
- CSS的块级元素和内联元素,以及float
说明:之前有一点搞错了,就是float其实是浮动起来,其它元素会位于它的底层. 最近在系统地学习HTML5,感觉补上了好多缺失的知识. 例如: 锚点定位其实可以通过 id 来实现: CSS 使用 !i ...
- e779. 获得JList中的已选项
The following methods return the indices of the selected items: // To create a list, see e774 创建JLis ...
- QIIME1 聚OTU
qiime 本身不提供聚类的算法,它只是对其他聚otu软件的封装 根据聚类软件的算法,分成了3个方向: de novo: pick_de_novo_otus.py ...
- Windows7下安装cpu版的Tensorflow
windows7下安装python3.5 1.下载python-3.5.2-amd64.whl https://www.python.org/downloads/release/python-352/ ...
- tftp
Ubuntu 12.04 tftp 设置 1.sudo apt-get install tftp-hpa tftpd-hpa 2.修改/etc/default/tftpd-hpa TFTP_USERN ...