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 ...
随机推荐
- Navi.Soft31.开发工具(含下载地址)
1系统简介 1.1功能简述 在软件开发过程中,我们需要经常对字符串.文件.数据库操作.有时需要浏览Json格式串,有时需要浏览Xml格式串,有时需要读取txt或excel文件,有时需要对数据库访问.本 ...
- 关于Unity中如何立即中断动画然后重新开始播放
今天做一个FPS游戏的时候,用的是新版的动画系统,遇到一个问题. 就是用枪打敌人的时候,敌人会播放一个被击中的动画,但是如果在动画播放的过程中再射击敌人,敌人会先把第一个被击中的动画播放完,才再播放第 ...
- Axiom3D:Ogre动画基本流程与骨骼动画
在Axiom中,Animation类用于管理动画,在此对象中主要管理着AnimationTrack对象,此对象用于管理动画的各种类型的每一桢.在Axiom中,动画类型主要有变形动画,姿态动画,骨骼动画 ...
- GROUP BY、HAVING、AS 的用法小例子
需求: 查询选休了5门课程的学生的姓名 分析: 1. 先从 t_sc 表中查出 选了5门课的学生的学号: SELECT COUNT(code) AS countCourse,sid FROM t_sc ...
- 嵌入式开发之uart---编程
下位机往上位机发送串口数据都是漫漫的这个包,但是win上位机往下位机发数据时,得分包大小,下位机收到的不一从1到200左右,大部分为100左右 http://bbs.csdn.net/topics/3 ...
- js 事件调度
var EventTarget = function () { this._listener = {}; }; EventTarget.prototype = { constructor: this, ...
- C# 实现数字字符串左补齐0的两种方法
); MessageBox.Show(sss); return; 代码如上,自动补齐前面的0
- C# 线程池执行操作例子
public partial class Form1 : Form { CountdownEvent hander = ); public static object lock_action = ne ...
- u3d加载外部视屏
u3d的外部加载视屏,采用www方式,可以使用gui播放,也可以绑定到gameobject上作为动态材质使用,不过目前只支持.ogg格式,需要转... using UnityEngine;using ...
- MacOS下MySQL配置
先去官网下载一个 MySQL for mac http://www.cnblogs.com/xiaobo-Linux/ 命令行运行终端,运行下面两条命令: 1 2 alias mysql=/usr/l ...