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. Mac OS, Mac OSX 与Darwin

    作为收购 NeXT 公司的结果,苹果公司获得了 NeXTSTEP 架构中的 Mach 和 Objective-C 等设计.尽管 NeXTSTEP 本身已经不再发展了,但是其中的组件在 OS X 中获得 ...

  2. 总结一些笔记上的C和C++知识点

    1.如果没有提供自己的copy构造函数,C++会提供一个默认的copy构造函数,是成员到成员的copy. 2.C中static的作用: 1.隐藏:如果未加static,编译多个文件的时候,所有的全局变 ...

  3. 技能UP:SAP OBYC自动记账的实例说明(含value String应用说明)

    一. 自动过账原理 在MM模块的许多操作都能实现在FI模块自动过账,如PO收货.发票验证(LIV).工单发料.向生产车间发料等等.不用说,一定需要在IMG中进行配置才可以实现自动处理.但SAP实现的这 ...

  4. Cisco无线控制器配置Radius

    使用Cisco无线控制器管理AP,配置Radius服务器,用于企业加密wifi的认证. 结合上一篇文档进行操作: http://www.cnblogs.com/helloworldtoyou/p/80 ...

  5. Java如何格式化24小时格式的时间?

    在Java中,如何格式化24小时格式的时间?? 此示例使用SimpleDateFormat类的sdf.format(date)方法将时间格式化为24小时格式(00:00-24:00). package ...

  6. django学习2 视图和模板

    1 编写更多的视图 polls/views.py def detail(request, question_id): return HttpResponse("You're looking ...

  7. ubuntu下查看windows的 txt 文件乱码

    在终端执行 gsettings set org.gnome.gedit.preferences.encodings auto-detected "['UTF-8','GB18030','GB ...

  8. 纯CSS3实现的顶部社会化分享按钮

    今天要分享一款纯CSS3实现的社会化分享按钮,它放置在网页的顶部,你可以选择将它固定在网页顶部,这样对用户分享内容就十分方便.这些社会化分享按钮的图标文件来自google和bootstrap的字体文件 ...

  9. 分享10款效果惊艳的HTML5图片特效

    在HTML5的世界里,图片特效都十分绚丽,我们在网站上也分享过很多不错的HTML5图片特效,现在我们精选10款效果惊艳的HTML5图片特效分享给大家. 1.HTML5 3D正方体旋转动画 很酷的3D特 ...

  10. opengl deferred shading

    原文地址:http://www.verydemo.com/demo_c284_i6147.html 一.Deferred shading技术简介 Deferred shading是这样一种技术:将光照 ...