|
|
<div id="cnblogs_post_body"> 最近很忙,既要外出找工作又要兼顾老板公司的项目。今天在公司,忙里偷闲,总结一下.NET中的异步调用函数的实现方法,DebugLZQ在写这篇博文之前自己先动手写了本文的所有示例代码,开写之前是做过功课的,用代码说话方有说服力。
本文的内容旨在用最简洁的代码来把异步调用的方法说清楚,园子里的高手老鸟可以绕行,不喜勿喷,非诚勿扰~
lz的前一篇文章简单的说了下异步,主要是从理解上来讲;这篇文章主要写具体的实现方法。实现异步编程有4种方法可供选择,这4种访求实际上也对应着4种异步调用的模式,分为&ldquo;等待&rdquo;和&ldquo;回调&rdquo;两大类。四种方法,我在代码中都进行了详细的注释,这里不罗嗦了,直接用代码说明吧
第一种方法:BeginEnvoke EndEnvoke方法,属于&ldquo;等待&rdquo;类。
<div class="cnblogs_code">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace 异步调用实现方法汇总{ /// <summary> /// 异步调用方法总结: /// 1.BeginEnvoke EndEnvoke /// 当使用BeginInvoke异步调用方法时,如果方法未执行完,EndInvoke方法就会一直阻塞,直到被调用的方法执行完毕 /// </summary> class Program { public delegate void PrintDelegate(string s); static void Main(string[] args) { PrintDelegate printDelegate = Print; Console.WriteLine("主线程"); IAsyncResult result= printDelegate.BeginInvoke("Hello World.", null, null); Console.WriteLine("主线程继续执行..."); //当使用BeginInvoke异步调用方法时,如果方法未执行完,EndInvoke方法就会一直阻塞,直到被调用的方法执行完毕 printDelegate.EndInvoke(result); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } public static void Print(string s) { Console.WriteLine("异步线程开始执行:"+s); Thread.Sleep(5000); } }} |
|