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. ecshop常用的一些变量

    <!-- {if $smarty.session.user_rank gt 1}-->gt大于 lt小于1:ecshop模板中调用session的值 {$smarty.session.us ...

  2. 安卓程序代写 网上程序代写[原]Android之Bluetooth编程

    ViewGroup 相关资料 : http://www.incoding.org/admin/archives/199.html http://bbs.csdn.net/topics/37014474 ...

  3. Chrome 各版本下载集合

    Windows平台: Chrome 在线安装包: 最新稳定版(Stable Channel)Chrome在线安装: [点击这里] 最新测试版(Beta Channel)Chrome在线安装: [点击这 ...

  4. freetds 移植

    移植freetds主要是为了能够在linux下,使用C语言访问微软的sqlserver数据库. 参考连接 http://blog.csdn.net/neighbor1000/article/detai ...

  5. 层层递进——宽度优先搜索(BFS)

    问题引入 我们接着上次“解救小哈”的问题继续探索,不过这次是用宽度优先搜索(BFS). 注:问题来源可以点击这里 http://www.cnblogs.com/OctoptusLian/p/74296 ...

  6. struts2系列(二):struts2参数传递错误、struts2的输入错误验证

    一.struts2参数传递错误 1. 基本数据类型的传递最好使用包装类,原因是struts 2.1之后使用基本数据类型如果参数为空会报错2. 日期参数的传递最好定义一个区域的属性(定义locale), ...

  7. application.properties详解 --springBoot配置文件

    本文转载:http://blog.csdn.net/lpfsuperman/article/details/78287265###; # spring boot application.propert ...

  8. PLSQL Developer删除奇葩表出现异常ORA-00942: 表或试图不存在

    简单描述一下问题:发现数据库里有两个名称相同的表,不同的是PLSQL Developer里一个表名显示是大写,而另一个表名显示是小写 一般情况下,无论建表语句是大写,还是小写,因Oracle是区分大小 ...

  9. 第一個shell腳本

    #!/bin/bash echo "Hello World !" 運行

  10. CCSprite: fade 效果切换图片

    //CCSprite+Animation.h #import "CCSprite.h" @interface CCSprite (Animation) + (void)fadeWi ...