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.

转:http://www.dotnetscraps.com/dotnetscraps/post/Explaining-Delegates-in-C-Part-6-(Asynchronous-Callback-Way-3).aspx

Explaining Delegates in C# - Part 6 (Asynchronous Callback - Way 3)的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 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, ...

  4. Synchronous/Asynchronous:任务的同步异步,以及asynchronous callback异步回调

    两个线程执行任务有同步和异步之分,看了Quora上的一些问答有了更深的认识. When you execute something synchronously, you wait for it to ...

  5. 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 ...

  6. 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 ...

  7. 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 ...

  8. [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 ...

  9. Delegates and Events

    People often find it difficult to see the difference between events and delegates. C# doesn't help m ...

随机推荐

  1. 安卓程序代写 网上程序代写[原]Android项目中string.xml占位符

    开发中经常遇到这样的情况 , 在string.xml中用到以下占位符 <string name="delete_success">删除<xliff:g id=&q ...

  2. Linux epoll版定时器

    #ifndef __MYTIMER_H_ #define __MYTIMER_H_ /*************** 高并发场景下的定时器 *****************/ //定时器回调函数 t ...

  3. Ubuntu中基于QT的系统网线连接状态的实时监视

    1.必要准备 需包: #include <QNetworkInterface> 2.实现获取当前的网线连接状态 以下是自己在网络上搜到的一个解决方法,且没有加入iface.flags(). ...

  4. HBase高性能复杂条件查询引擎

    转自:http://blog.csdn.net/bluishglc/article/details/31799255 mark 写在前面 本文2014年7月份发表于InfoQ,HBase的PMC成员T ...

  5. 关于Unity中Cg的基本语法和使用

    Cg是类似于C语言的发展起来的图形编程语言,Cgraphics,它的很多表达式if...else...和C语言非常相像,也和C#非常相像. 由于Shader是写给显卡执行的,所以没有输出语句来调试,很 ...

  6. 关于Unity的开发思路

    我现在的思路大概是这样的,2D游戏 Hierachy视图 有一个总的Canvas节点,挂载一个总的游戏控制脚本game_scene,下面有这样一些子节点 1.game_root:下面存放游戏界面中的物 ...

  7. mxnet img2rec的使用,生成数据文件

    建立文件夹 制作lst文件,即生成train.lst文件python im2rec.py ./mxrec/train ./mxdata --list --recursive train.lst文件格式 ...

  8. 嵌入式开发之hisilicon---hi3536 处理器简介

    (1)处理器概述 (2)处理器模块架构 --------------author:pkf -------------------time:7-19 -------------------------- ...

  9. Opengl的gl_NormalMatrix

    原文地址:http://blog.csdn.net/ichild1964/article/details/9728357 参考:http://www.gamedev.net/topic/598985- ...

  10. unity3d 读取usb摄像头

    using UnityEngine; using System.Collections; public class C : MonoBehaviour { private WebCamTexture ...