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. OSPF中 hello报文的 内容

    邻居关系通过hello报文来建立.Hello报文中包含如下一些内容: 1.始发路由器的router-id 2.始发路由器接口的area-id 3.始发路由器接口的地址掩码 4.始发路由器接口的auth ...

  2. SAP HR模块的基础数据表和增强配置

    信息类型是SAP HR模块数据单元,用于对人员数据的记录和维护,是HR的基础.信息类型按照其创建方式的不同可以分为:人事信息类型.组织信息类型.信息类型数据的维护主要在事物码PA30.PA40.po1 ...

  3. 关于sdl_ttf使用字体库加载失败的问题

    今天同事拿着前期阶段开发的视频绘图库给另外一个同事的电脑上测试,结果发现老是出现打开字体库失败,但从打印的日志信息看,路径下确实存在字体库啊,这是什么原因? 于是没办法,搬到自己本级上再测试下,从他机 ...

  4. Xianfeng轻量级Java中间件平台:基于RBAC模型实现权限控制的原理

    首先,白话一下RBAC模型.RBAC是基于角色的访问控制(Role-Based Access Control)的简称.RBAC认为权限授权实际上是Who.What.How的问题.在RBAC模型中,wh ...

  5. js 跨域 Jquery取得iframe中元素的几种方法

    http://www.jb51.net/article/34942.htm 收集利用Jquery取得iframe中元素的几种方法 : 父页面访问子页面 $(document.getElementByI ...

  6. C# 异常和异常处理

    C# 语言的异常处理功能可帮助您处理程序运行时出现的任何意外或异常情况. 异常处理使用 try.catch 和 finally 关键字尝试某些操作,以处理失败情况,尽管这些操作有可能失败,但如果您确定 ...

  7. MyBatis中对于字符串blank(null、empty)的判定方法

    直接上代码,关键需要进行2个判定,一个是null判定,一个是 ‘’ 判定. <where> <if test="url!= null and url!=''"&g ...

  8. tp5数据输出

    法一:系统配置 'default_return_type'=>'json' 法二:输出设置 namespace app\index\controller; class Index { publi ...

  9. springboot+shiro+redis(单机redis版)整合教程

    相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(集群redis版)整合教程 3.springboot+shiro+redis(单机red ...

  10. springmvc接口ios网络请求

    springmvc:   application/json;charset=utf-8的ios网络请求: 后台使用 @RequestBody注解参数接收: