.NET Framework 允许异步调用任何方法,为了实现异步调用目标,需要定义与被调用方法具有相同签名的委托。公共语言运行时会自动使用适当的签名为该委托定义 BeginInvoke 和 EndInvoke 方法,也就是说委托的 BeginInvoke 和 EndInvoke 方法是自动生成的,无需定义。所谓的异步调用,指的是在新线程中执行被调用的方法。
  BeginInvoke 方法启动异步调用, 该方法与要异步执行的方法具有相同的参数,还有另外两个可选参数。第一个参数是一个 AsyncCallback 委托,该委托引用在异步调用完成时要调用的方法。 第二个参数是一个用户定义的对象,该对象将信息传递到回调方法。BeginInvoke 立即返回,不等待异步调用完成。 BeginInvoke 返回一个 IAsyncResult,后者可用于监视异步调用的进度。
  采用BeginInvoke 和 EndInvoke实现方法的异步调用共有四种方式,下面用演示代码分别说明。代码示例演示异步调用一个长时间运行的方法 TestMethod 的各种方式。 TestMethod 方法会显示一条控制台消息,说明该方法已开始处理,方法所在的线程,休眠了几秒钟,然后结束。 TestMethod 有一个 out 参数,用于说明此类参数添加到 BeginInvoke 和EndInvoke 的签名中的方式,可以按同样的方式处理 ref 参数。

        public static string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("方法的执行线程ID: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("My call time was {0}.", callDuration.ToString());
}

  定义相应的委托类型

 public delegate string AsyncDelegate(int  callDuration, out int threadId);

1 使用 EndInvoke阻塞调用线程,直到异步调用结束

  异步执行方法的最简单方式是通过调用委托的 BeginInvoke 方法来开始执行方法,可以在在调用线程上执行一些其他操作,然后调用委托的 EndInvoke 方法。 EndInvoke 会阻塞调用线程,直到异步调用完成后才返回。

   

namespace TestInvoke
{
public delegate string AsyncDelegate(int callDuration, out int threadId);
class Program
{
static void Main(string[] args)
{
//输出主线程ID
Console.WriteLine("主线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
//创建委托
AsyncDelegate asyncDel = new AsyncDelegate(TestMethod);
int nThreadID = ; //异步执行TestMethod方法
IAsyncResult result = asyncDel.BeginInvoke(, out nThreadID, null, null);
//阻塞调用线程
asyncDel.EndInvoke(out nThreadID, result); Console.ReadKey();
} public static string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("方法的执行线程ID: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("My call time was {0}.", callDuration.ToString());
}
}
}

  调用线程会被阻塞3秒钟,程序输出为:

  

2 使用 WaitHandle 等待异步调用

  使用由 BeginInvoke 返回的 IAsyncResult 的 AsyncWaitHandle 属性来获取 WaitHandle。 异步调用完成时, WaitHandle 会收到信号,可以通过调用 WaitOne 方法等待它。

  如果您使用 WaitHandle时,在调用 EndInvoke 检索结果之前,还可以执行其他处理。

  

        static void Main(string[] args)
{
//输出主线程ID
Console.WriteLine("主线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
//创建委托
AsyncDelegate asyncDel = new AsyncDelegate(TestMethod);
int nThreadID = ; //异步执行TestMethod方法
IAsyncResult result = asyncDel.BeginInvoke(, out nThreadID, null, null);
//阻塞调用线程
WaitHandle handle = result.AsyncWaitHandle;
handle.WaitOne(); //其他操作 //终止异步调用,通过返回值取得调用结果
string returnValue = asyncDel.EndInvoke(out nThreadID, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
nThreadID, returnValue); Console.ReadKey();
}

3轮询异步调用完成

  可以使用由 BeginInvoke 返回的 IAsyncResult 的 IsCompleted 属性来判断异步调用何时完成。

        static void Main(string[] args)
{
//输出主线程ID
Console.WriteLine("主线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
//创建委托
AsyncDelegate asyncDel = new AsyncDelegate(TestMethod);
int nThreadID = ; //异步执行TestMethod方法
IAsyncResult result = asyncDel.BeginInvoke(, out nThreadID, null, null); //轮询异步执行状态
while (true)
{
if (result.IsCompleted)
{
break;
}
Thread.Sleep();
} //终止异步调用,通过返回值取得调用结果
string returnValue = asyncDel.EndInvoke(out nThreadID, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
nThreadID, returnValue); Console.ReadKey();
}

4 异步调用完成时执行回调方法 

  如果调用的线程不需要的异步执行函数的返回值,则可以在调用完成时执行回调方法,回调方法在 ThreadPool 里的异步线程上执行。

若要使用回调方法,必须将表示回调方法的 AsyncCallback 委托传递给 BeginInvoke。 也可以传递包含回调方法要使用的信息的对象。在回调方法中,可以将 IAsyncResult(回调方法的唯一参数)强制转换为 AsyncResult 对象。 然后,可以使用AsyncResult .AsyncDelegate 属性获取已用于启动调用的委托,以便可以调用 EndInvoke。

  • TestMethod 的 threadId 参数为 out 参数,因此 TestMethod 从不使用该参数的输入值。  如果 threadId 参数为 ref 参数,则该变量必须为类级别字段,这样才能同时传递给 BeginInvoke 和 EndInvoke。

  • 传递给 BeginInvoke 的状态信息是一个格式字符串,所以状态信息必须强制转换为正确的类型才能被使用。

  • 回调在 ThreadPool 线程上执行。 ThreadPool 线程是后台线程,这些线程不会在主线程结束后保持应用程序的运行,因此示例的主线程必须休眠足够长的时间以便回调完成。

  

       static void Main(string[] args)
{
//输出主线程ID
Console.WriteLine("主线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
//创建委托
AsyncDelegate asyncDel = new AsyncDelegate(TestMethod);
int nThreadID = ; //异步执行TestMethod方法,使用回调函数并传入state参数
IAsyncResult result = asyncDel.BeginInvoke(, out nThreadID,
new AsyncCallback(AsyncCallCompleted), "测试参数传递"); Console.ReadKey();
} public static void AsyncCallCompleted(IAsyncResult ar)
{
Console.WriteLine("AsyncCallCompleted执行线程ID:{0}",Thread.CurrentThread.ManagedThreadId); //获取委托对象
System.Runtime.Remoting.Messaging.AsyncResult result = (System.Runtime.Remoting.Messaging.AsyncResult)ar;
AsyncDelegate asyncDel = (AsyncDelegate)result.AsyncDelegate; //获取BeginInvoke传入的的state参数
string strState = (string)ar.AsyncState;
Console.WriteLine("传入的字符串是{0}",strState); //结束异步调用
int nThreadID;
string strResult = asyncDel.EndInvoke(out nThreadID, ar); Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".",
nThreadID, strResult);
} public static string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("TestMethod方法的执行线程ID: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("My call time was {0}.", callDuration.ToString());
}

  输出结果为

  

总结

    除了第4种采用回调函数的方式外,其他三种方式均会阻塞调用线程。

委托的BeginInvoke和EndInvoke方法的更多相关文章

  1. 异步使用委托delegate --- BeginInvoke和EndInvoke方法

    当我们定义一个委托的时候,一般语言运行时会自动帮委托定义BeginInvoke 和 EndInvoke两个方法,这两个方法的作用是可以异步调用委托. 方法BeginInvoke有两个参数: Async ...

  2. C#线程系列讲座(1):BeginInvoke和EndInvoke方法

    一.C#线程概述 在操作系统中一个进程至少要包含一个线程,然后,在某些时候需要在同一个进程中同时执行多项任务,或是为了提供程序的性能,将要执行的任务分解成多个子任务执行.这就需要在同一个进程中开启多个 ...

  3. [转]BeginInvoke和EndInvoke方法浅析

    开发语言:C#3.0   IDE:Visual Studio 2008   一.C#线程概述   在操作系统中一个进程至少要包含一个线程,然后,在某些时候需要在同一个进程中同时执行多项任务,或是为了提 ...

  4. delegate 中的BeginInvoke和EndInvoke方法

    开发语言:C#3.0 IDE:Visual Studio 2008 一.C#线程概述 在操作系统中一个进程至少要包含一个线程,然后,在某些时候需要在同一个进程中同时执行多项任务,或是为了提供程序的性能 ...

  5. 转:C#线程系列讲座(1) BeginInvoke和EndInvoke方法

    转载自:http://www.cnblogs.com/levin9/articles/2319248.html 开发语言:C#3.0IDE:Visual Studio 2008本系列教程主要包括如下内 ...

  6. 黄聪:C#多线程教程(1):BeginInvoke和EndInvoke方法,解决主线程延时Thread.sleep柱塞问题(转)

    开发语言:C#3.0 IDE:Visual Studio 2008 本系列教程主要包括如下内容: 1.  BeginInvoke和EndInvoke方法 2.  Thread类 3. 线程池 4. 线 ...

  7. C# BeginInvoke和EndInvoke方法

    转载自:BeginInvoke和EndInvoke方法 IDE:Visual Studio 2008 本系列教程主要包括如下内容:1. BeginInvoke和EndInvoke方法 2. Threa ...

  8. BeginInvoke和EndInvoke方法

    本系列教程主要包括如下内容:1. BeginInvoke和EndInvoke方法 2. Thread类 3. 线程池 4. 线程同步基础 5. 死锁 6. 线程同步的7种方法 7. 如何在线程中访问G ...

  9. BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题

    BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题 原文:http://www.sufeinet.com/thread-3707-1-1.html      大家可以先看看我上 ...

随机推荐

  1. 一个3D视频播放器的演示APK

    介绍: 这个APK是把视频显示分割成左右对等的两幅画面.同时无缝显示在屏幕上, 配合类似谷歌的cartdboard "纸片壳" 或市面上的魔镜等3D眼镜来播放视频画面, 根据3D眼 ...

  2. Docker 总结

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[+] Docker总结 简单介绍 1 Docker 架构 安装和环境配置 1 mac 11 brew安装 11 dmg文件安装 1 ...

  3. MySQL安装之zip格式

    背景: 今天本来想学点JDBC的,没想到在MySQL的安装上卡了很久,特此写下此文,希望大家遇到类似问题可以早些跳出坑.   一.寻找资源 今天,为了学习JDBC,准备在公司的电脑上装MySQL,于是 ...

  4. xfs文件系统磁盘配额

    引言 这篇文章简单介绍一下xfs文件系统的磁盘配额配置. 文章目录 0×1.开启分区磁盘配额 0×2.使用xfs_quota命令配置磁盘配额 0×1.开启分区磁盘配额 对于ext4文件以前的文件系统, ...

  5. qemu毒液漏洞分析(2015.9)

    0x00背景 安全娱乐圈媒体Freebuf对该漏洞的有关报道: 提供的POC没有触发崩溃,在MJ0011的博客给出了修改后可以使qemu崩溃的poc.详见: http://blogs.360.cn/b ...

  6. sql convert() 函数

    convert: 时间格式转换为其他时间格式的函数 CONVERT ( data_type [ ( length ) ] , expression [ , style ] )   data_type: ...

  7. HDU 2177 取(2堆)石子游戏 (威佐夫博弈)

    题目思路:威佐夫博弈: 当当前局面[a,b]为奇异局时直接输出0 否则: 1.若a==b,输出(0 0): 2.将a,b不停减一,看能否得到奇异局,若有则输出: 3.由于 ak=q*k(q为黄金分割数 ...

  8. 解决getElementsByClassName兼容问题

    getElementsByClassName这个方法很常用,但是只有较新的浏览器才兼容,所以我们需要自己写个方法,解决这个问题,使它能够兼容各个浏览器. function getElementsByC ...

  9. chrom 快捷键 整理版

    chrome窗口和标签页快捷键: Ctrl+N 打开新窗口 Ctrl+T 打开新标签页 Ctrl+Shift+N 在隐身模式下打开新窗口 Ctrl+O,然后选择文件 在谷歌浏览器中打开计算机上的文件 ...

  10. jQuery(4)—— jQuery中的事件

    jQuery中的事件 [加载DOM] 在常规的JavaScript代码中,通常使用window.onload方法,在jQuery中,使用的是$(document).ready()方法.极大地提高了we ...