This is the final part of the series that started with...

Callback and Multicast delegates
One more Event
Asynchronous Callback - Way 1 - BeginInvoke > EndInvoke
Asynchronous Callback - Way 2 - BeginInvoke > AsyncWaitHandle.WaitOne(x) > EndInvoke > AsynWaitHandle.Close()
Asynchronous Callback - Way 3 - BeginInvoke > Poll for result's IsCompleted > EndInvoke

In this scenario, if we go with the husband-wife-kiddo analogy, I will need to introduce another guy! No no no... please don't misunderstand me... he is the just the driver 

So, now the husband drops his wife at the mall. And instead of coming back to pick her up, he simply says... honey, I am going to the office. When you are done shopping,  call the driver (+91-97415-xxxxx) and he would take you home.

NOTE >

  • As soon as the main thread calls the asynchronous method, his part is done
  • The callback method is executed on the ThreadPool thread
  • The call to BeginInvoke (so far... it has been something like... caller.BeginInvoke(25, out threadId, null, null);) would now have the 3rd parameter as an AsyncCallback which contains the callback method name.
  • The 4th parameter takes an object which your callback method might like to use
  • The ThreadPool threads are background threads. This means that they won't keep the application running in case the main thread ends. Thus, the main thread has to be alive for long enough to ensure that the background threads are done processing.

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;
using System.Runtime.Remoting.Messaging; 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)
{
threadID = Thread.CurrentThread.ManagedThreadId;
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);
}
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 and pass the callback method's name
// 2. Do some work on the main thread
// 3. Your callback method is called when the processing completes.
// 4. Retrieve the delegate and 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); //This is a dummy variable since this thread is not supposed to handle the callback anyways!!!
int dummy = ;
//Start the asynchronous call with the following parameters...
//Parameter 1 = 30 > In my example the tortoise class will now do something for 30 seconds
//Parameter 2 = Dummy variable, just to get the output of the threadID
//Parameter 3 = new AsyncCallback(CallbackMethod) > This is the method which would be called once the async task is over
//Parameter 4 = Object > This is a string which would display the information about the async call
IAsyncResult result = caller.BeginInvoke(, out dummy, new AsyncCallback(CallThisMethodWhenDone),
"The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); //The callback method will use a thread from the ThreadPool.
//But the threadpool threads are background threads. This implies that if you comment the line below
//you would notice that the callback method is never called, since the background threads can't stop the main
//program to terminate!
Thread.Sleep();
Console.WriteLine("The main thread ends. Change the value 3000 in code to 40000 and see the result");
} //The signature for the call back method must be same System.IAsyncResult delegate.
static void CallThisMethodWhenDone(System.IAsyncResult ar)
{
//To retrieve the delegate we will cast the IAsyncResult to AsyncResult and get the caller
AsyncResult result = (AsyncResult)ar;
TortoiseCaller caller = (TortoiseCaller)result.AsyncDelegate; //Get the object (in our case it is just a format string) that was passed while calling BeginInvoke!
string formattedString = (string)ar.AsyncState; // Define a variable to receive the value of the out parameter.
// If the parameter were ref rather than out then it would have to
// be a class-level field so it could also be passed to BeginInvoke.
//The following variable would take the Thread ID
int threadId = ; //At this point, the threadID won't be a dummy variable as it was in the Main method
//We are passing threadID to get the output from the TortoiseMethod
string returnValue = caller.EndInvoke(out threadId, ar); //Use the format string to format the output message.
Console.WriteLine(formattedString, threadId, returnValue);
}
}
}

There will be more on Delegates and Asynchronous programming going forward.

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

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

  1. Explaining Delegates in C# - Part 6 (Asynchronous Callback - Way 3)

    By now, I have shown the following usages of delegates... Callback and Multicast delegatesEventsOne ...

  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. linux mongodb数据库的安装

    折腾两天, 前领导留下的烂摊子,前天忽然挂掉了, 整个公司就我会linux, 奶奶的, 一言难尽. 下面记录下怎么安装mongodb, 前面是从菜鸟教程复制来的 1. 下载 MongoDB 提供了 l ...

  2. 【Python】Centos + gunicorn+flask 报错ImportError: No module named request

    今天用Python去下载图片,用到了 urllib.request,这个是python3的方法.python2 使用的是urllib2 遇到了这么个问题后台报错,ImportError: No mod ...

  3. android 8 wifi wifi 扫描过程

    查看一下android wifi扫描的过程. packages\apps\Settings\src\com\android\settings\wifi\WifiSettings.java public ...

  4. 网络中TCP、IP、MAC、UDP的头部格式信息

    TCP头部格式 字段名称 长度(比特) 含义 TCP头部(20字节~) 发送方端口号 16 发送网络包的程序的端口号 接收方端口号 16 网络包的接收方程序的端口号 序号(发送数据的顺序编号) 32 ...

  5. SpringBoot系列六:SpringBoot整合Tomcat

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Tomcat 2.背景 SpringBoot 本身支持有两类的 WEB 容器:默认的 To ...

  6. Mybatis系列(三):Mybatis实现关联表查询

    原文链接:http://www.cnblogs.com/xdp-gacl/p/4264440.html 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 ...

  7. python3 pyodbc简单使用

    转自:https://my.oschina.net/zhengyijie/blog/35587 1.连接数据库 首先要import pyodbc 1)直接连接数据库和创建一个游标(cursor) cn ...

  8. unity---------------------关于BuildAssetBundles的使用(打包)

    using UnityEditor;using UnityEngine; public class BuildAssetBundle{ /// <summary> /// 点击后,所有设置 ...

  9. JAXB:Java对象序和XML互相转化的利器

    JAXB(Java Architecture for XML Binding简称JAXB)允许Java开发人员将Java类映射为XML表示方式.JAXB提供两种主要特性:将一个Java对象序列化为XM ...

  10. 一款标注颜色,距离的小软件 markman

    长度标记   坐标和矩形标记   色值标记   文字标记   长度自动测量   标记拖拽删除   支持多种图片格式 支持PSD(需用最大兼容保存).PNG.BMP.JPG格式 设计稿自动刷新 在标注的 ...