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, which is a little better than Way 1. In the previous post, it was like a husband telling his wife...
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.
Notice that, although it looks like a good way of getting the work done, it has a tiny flaw (not really a flaw, but I will still call it a flaw to make my story!). What if their 6 year old kid called the husband in the meantime? Would the husband appreciate it while waiting he can do nothing else but wait? I mean, what if he has to just pick up the phone and tell his child, you know kiddo, I am here at the mall waiting for your mom. I'll be back in some time! This example just does that. Basically, we know that EndInvoke is a blocking call. If you make this call, you can do nothing but wait, which may make your UI look awful. In this example, we will be waiting for the async call to complete, but still be free enough to do some stuff.
Okay, enough said... let's take a look at the code (in fact, it is always better to run it!!!)
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. Call the result's AsyncWaitHandle.WaitOne() which would be a blocking call
// 4. Call EndInvoke which won't be a blocking call this time!
// 5. Close the result's AsyncWaitHandle, explicitly.
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("Perform more work as the other thread works...");
for (int i = ; i > ; i--)
{
Thread.Sleep();
Console.WriteLine("{0}...", i);
}
Stopwatch s = new Stopwatch();
//Calling WaitOne is a blocking call. As soon as you call WaitOne, you won't proceed further
//in this main thread until the Async call completes
Console.WriteLine("Before calling WaitOne... {0} milliseconds", s.ElapsedMilliseconds.ToString());
s.Start();
//The next call can be a blocking call (in our case it WILL be a blocking call since the Tortoise
//method takes 30 seconds to complete. By now, already 12 seconds are over!
result.AsyncWaitHandle.WaitOne();
//The good thing is that, now you can do update the client while still waiting for the call to complete
Console.WriteLine("Well, I know waiting could be boring, but at the moment I am still waiting...");
//Waiting for 5 seconds now!
result.AsyncWaitHandle.WaitOne();
//Updating once again...
Console.WriteLine("Argghh... when will this end??");
//Waiting till the async call is complete (Notice that this can be blocking!!)
result.AsyncWaitHandle.WaitOne();
s.Stop();
Console.WriteLine("After calling WaitOne... {0} milliseconds", s.ElapsedMilliseconds.ToString());
//Notice that this call will NOT be a blocking call as it was in our previous example!
string returnValue = caller.EndInvoke(out threadId, result);
//Close the wait handle. This is important, since it is not automatically cleared.
//Only the next GC can collect this native handle. So, it is a good practise to clear
//this handle as soon as you are done with it.
result.AsyncWaitHandle.Close();
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 5 (Asynchronous Callback - Way 2)的更多相关文章
- 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 4 (Asynchronous Callback - Way 1)
So far, I have discussed about Callback, Multicast delegates, Events using delegates, and yet anothe ...
- 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 ...
随机推荐
- Sword protobuf学习三
#include <iostream> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> ...
- Three ways to make your WPF images pop out on MouseOver
There are a couple of ways in WPF to make an image pop out when moving mouse over it. Of course we w ...
- Airtest 网易 UI 自动化工具 Airtest 浅用记录
一 使用目的 该工具主要是面向游戏UI测试基于图像识别,如游戏框架unity,Cocos-js以及网易内部的游戏框架同时也支持原生Android App 的基于元素识别的UI自动化测试.本文主要使用目 ...
- 【转】【WPF】WPF绑定用法
一.简介 为了后面行文顺利,在进入正文之前,我们首先对本文所涉及到的绑定知识进行简单地介绍.该节包含绑定的基本组成以及构建方式. WPF中的绑定完成了绑定源和绑定目标的联动.一个绑定常常由四部分组成: ...
- 使用Maven模板创建项目
在本教程中,我们将向你展示如何使用mvn archetype:generate从现有的Maven模板列表中生成项目.在Maven 3.3.3,有超过1000+个模板,Maven 团队已经过滤掉一些无用 ...
- 创建Swing的步骤
(1)导入Swing包 (2)选择界面风格 (3)设置顶层容器 (4)设置按钮和标签 (5)将组件放到容器上 (6)为组件增加边框 (7)处理事件 (8)辅助技术支持 package Com.MySw ...
- MySQL查看某库表大小及锁表情况
查询所有数据库占用磁盘空间大小的SQL语句: 语句如下: select TABLE_SCHEMA, concat(truncate(sum(data_length)/1024/1024,2),' MB ...
- 【阿里云】WindowsServer2012 搭建FTP站点 图文记录
配置说明: 服务商:阿里云 系统: WindowsServer2012 一:配置FTP服务器 1.进入操作系统,直接从启动栏打开服务器管理器,选择添加功能和角色 2.选择服务器 3.勾选FTP服务器选 ...
- 数据源(HikariCP)
HikariCP 是一个高性能的 JDBC 连接池组件.下图是性能的比较测试结果: 自从看到了这张图,我就对于我之前一直在使用了 c3p0 产生了深深的怀疑,迫切的期望得到对应的数据来优化我的代码. ...
- Spring核心框架体系结构(jar包引用分析)[转]
很多人都在用spring开发java项目,普通添加lib目录拷贝jar包,或者创建maven项目时,配置maven依赖的时候并不能明确要配置哪些spring的jar,经常是胡乱添加一堆,编译或运行报错 ...