Explaining Delegates in C# - Part 6 (Asynchronous Callback - Way 3)
By now, I have shown the following usages of delegates...
Callback and Multicast delegates
Events
One more Event
Asynchronous Callback - Way 1 - BeginInvoke > EndInvoke
Asynchronous Callback - Way 2 - BeginInvoke > AsyncWaitHandle.WaitOne(x) > EndInvoke > AsynWaitHandle.Close()
In this part, we will take a look at how you could use polling to figure out if the Asynchronous call is complete. So, to carry on with the Husband-Wife analogy from my previous posts, the present scenario would be something like... the husband leaves his wife at the mall for shopping, comes back and is waiting in the parking lot for his wife. He knows that their kid is waiting at their home, so he keeps calling his wife every N minutes, and then calls his kid to say... sorry kiddo, another few moments!!! In the code that follows the person looking at the UI is the kiddo, main thread = husband, and the thread doing asynchronous stuff is wife.
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; 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 thread # {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. Keep polling using result's IsCompleted property
// 4. 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);
//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);
//After calling the method asynchronously, the main thread continues to work...
Console.WriteLine("After making the Async call... Thread ID = {0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Start the polling...\nWaiting for the Tortoise method to complete...");
//The IAsynResult interface uses IsCompleted property which you can use to figure out if the call is complete
//Notice that this will be a blocking call until the Async call completes.
while (result.IsCompleted == false)
{
Console.Write(".");
Thread.Sleep();
}
//Normally, EndInvoke would be a blocking call, but in this case... it won't be.
//The reason is that we now know that the Async call is completed!
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("\nThe 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 6 (Asynchronous Callback - Way 3)的更多相关文章
- 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 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 ...
随机推荐
- android studio 解析Excel数据格式导入poi-3.17.jar时的一系列报错及处理Failed resolution of: Ljavax/xml/stream/XMLEventFactory,duplicate entry: org/apache/xmlbeans/xml/stream/Location.class,GC overhead limit exceeded
在org官网下载的poi jar包,导入到studio compile files('libs/poi-3.17.jar') compile files('libs/poi-ooxml-3.17.ja ...
- 我写的javascript常用静态方法类,分享给大家
util=function(){ return { $:function(id){ return document.getElementById(id); ...
- 关于Unity中FPS第一人称射击类游戏制作(专题十)
当前Unity最新版本5.6.3f1,我使用的是5.5.1f1 场景搭建 1: 导入人物模型, 手持一把枪;2: 导入碎片模型;3: 创建一个平面;4: 创建一个障碍物;5: 导入人物模型;6: 配置 ...
- 单表多个Count 条件进行查询拼接小妙用
单表多数据进行拼接 DROP table if EXISTS tmp_table; CREATE TEMPORARY TABLE tmp_table ( 创建临时表 SELECT p1q04,p2q0 ...
- Visual Studio主题与配色方案
有个性的开发人员总是喜欢使用属于的主题和配色方案,它们可以看出开发者的个性,更改它们可以缓解审美疲劳,总之选择一个适合自己的解决方案可能极大的增加自己的编码舒适度. 配色方案的选择和使用 手动修改Vi ...
- 正则表达式-----------------------------------C#的正则表达式
为了避免以后这样的情况,在此记录下正则表达式的一些基本使用方法附带小的实例.让以后在使用时能一目了然知道他的使用,为开发节约时间,同时也分享给大家 正则元字符 在说正则表达式之前我们先来看看通配符,我 ...
- php可选缓存APC
1.APC缓存简介 APC,全称是Alternative PHP Cache,官方翻译叫”可选PHP缓存”.它为我们提供了缓存和优化PHP的中间代码的框架. APC的缓存分两部分:系统缓存和用户数据缓 ...
- Couchbase 集群小实践
局域网 两台机 192.168.1.2 我们称为A机器 192.168.1.3 我们称为B机器 配置集群的时候,从A或者是B的web后台都可以添加, 在这里 我们以 A机器为主 目 ...
- Tomcat5内存简单优化
tomcat版本:apache-tomcat-5.5.28 解压版tomcat 修改catalina.bat文件,在开头添加如下内容: JAVA_OPTS='-Xms1024m -Xmx2048m - ...
- C# 中base和this关键字
base: 用于在派生类中实现对基类公有或者受保护成员的访问,但是只局限在构造函数.实例方法和实例属性访问器中. MSDN中小结的具体功能包括: ()调用基类上已被其他方法重写的方法. ()指定创建派 ...