Explaining Delegates in C# - Part 7 (Asynchronous Callback - Way 4)
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!).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Runtime.Remoting.Messaging; 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)
{
threadID = Thread.CurrentThread.ManagedThreadId;
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 thread # {0}", 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 and pass the callback method's name
// 2. Do some work on the main thread
// 3. Your callback method is called when the processing completes.
// 4. Retrieve the delegate and call EndInvoke which won't be a blocking call this time!
public class TortoiseConsumer
{
static void Main()
{
//Instantiate a new TortoiseClass
TortoiseClass tc = new TortoiseClass();
//Let's create the delegate now
TortoiseCaller caller = new TortoiseCaller(tc.TortoiseMethod); //This is a dummy variable since this thread is not supposed to handle the callback anyways!!!
int dummy = ;
//Start the asynchronous call with the following parameters...
//Parameter 1 = 30 > In my example the tortoise class will now do something for 30 seconds
//Parameter 2 = Dummy variable, just to get the output of the threadID
//Parameter 3 = new AsyncCallback(CallbackMethod) > This is the method which would be called once the async task is over
//Parameter 4 = Object > This is a string which would display the information about the async call
IAsyncResult result = caller.BeginInvoke(, out dummy, new AsyncCallback(CallThisMethodWhenDone),
"The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); //The callback method will use a thread from the ThreadPool.
//But the threadpool threads are background threads. This implies that if you comment the line below
//you would notice that the callback method is never called, since the background threads can't stop the main
//program to terminate!
Thread.Sleep();
Console.WriteLine("The main thread ends. Change the value 3000 in code to 40000 and see the result");
} //The signature for the call back method must be same System.IAsyncResult delegate.
static void CallThisMethodWhenDone(System.IAsyncResult ar)
{
//To retrieve the delegate we will cast the IAsyncResult to AsyncResult and get the caller
AsyncResult result = (AsyncResult)ar;
TortoiseCaller caller = (TortoiseCaller)result.AsyncDelegate; //Get the object (in our case it is just a format string) that was passed while calling BeginInvoke!
string formattedString = (string)ar.AsyncState; // Define a variable to receive the value of the out parameter.
// If the parameter were ref rather than out then it would have to
// be a class-level field so it could also be passed to BeginInvoke.
//The following variable would take the Thread ID
int threadId = ; //At this point, the threadID won't be a dummy variable as it was in the Main method
//We are passing threadID to get the output from the TortoiseMethod
string returnValue = caller.EndInvoke(out threadId, ar); //Use the format string to format the output message.
Console.WriteLine(formattedString, threadId, returnValue);
}
}
}
There will be more on Delegates and Asynchronous programming going forward.
Explaining Delegates in C# - Part 7 (Asynchronous Callback - Way 4)的更多相关文章
- 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 4 (Asynchronous Callback - Way 1)
So far, I have discussed about Callback, Multicast delegates, Events using delegates, and yet anothe ...
- 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 ...
随机推荐
- fresco中设置占位/加载失败的图片 无效
在xml中设置 placeholderImage 属性无效.代码如下: <com.facebook.drawee.view.SimpleDraweeView android:id=" ...
- android 避免线程的重复创建(HandlerThread、线程池)
最近在android开发中,用到都是new Thread(){...}.start()这种方式.本来这样是可以,但是最近突然爆出Performing stop of activity that is ...
- C++中,int a = 10的后面的操作
在C++中,int a = 10的内存表现形式取决于你的具体代码和优化级别,主要的几种形式: 不存在于内存中.比如a从未改变,被编译器当成常量,所有代码中的a直接替换成10: 存在于寄存器中:比如对a ...
- 自然语言交流系统 phxnet团队 创新实训 项目博客 (三)
语音转文本部分是调用的科大讯飞的在线语音,它的激发方式是按键,通过按钮触发开启安卓设备的录音,此部分需要在源码中写入关于安卓权限的要求,来调用安卓的录音权限,当按钮被激发,则开始进入语音录制阶段,将麦 ...
- Semantic segmentation using adversarial networks
FAIR Paris分部的论文,NIPS2016 Workshop. Motivation是让predict出来的结果和真实label在高层感觉上有一致性. 基本思想就是用GAN来区分segmenta ...
- tornado上传大文件以及多文件上传
tornado上传大文件问题解决方法 tornado默认上传限制为低于100M,但是由于需要上传大文件需求,网上很多说是用nginx,但我懒,同时不想在搞一个服务了. 解决方法: server = H ...
- IO多路复用的机制:select、poll、epoll
select.poll.epoll之间的区别总结[整理] IO多路复用之epoll总结 我读过的最好的epoll讲解--转自”知乎“
- Android开源库项目集锦
一.兼容类库 ActionBarSherlock : Action Bar是Android 3.0后才開始支持的,ActionBarSherlock是让Action Bar功能支持2.X后的全部平台. ...
- NPOI 2.1.1 系列(1) 使用NPOI读取 Excel文档 ;NpoiExcelHelper 导入导出 2003格式 2007格式的 Excel; Npoi 导出 xlsx 格式
下载地址 http://npoi.codeplex.com/releases 下面放一个 NPOIHelper 助手类吧,也不是我写的- NpoiExcelHelper 可以生成xlsx格式publi ...
- 【.NET】正则表达式笔记
很早就听说正则表达式的强大,今天终于一睹它的真容,在这里记下学习时候的笔记,以便以后查看 1.正则表达式 用于描述字符串规则的的特殊的字符(正则表达式本身是字符串,用来描述字符串的相关规则,用于与其他 ...