分类目录

链接

2012年 11月
 1234
567891011
12131415161718
19202122232425
2627282930  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET > 正文
.NET回调异步编程
.NET 暂无评论 阅读(1,784)

.NET中BeginInvoke等异步方法要等待异步方法执行完毕后才能拿到执行的结果,期间主线程均处于等待状态。而回调和它们最大的区别是,在调用 BeginInvoke时只要提供了回调方法,那么主线程就不必要再等待异步线程工作完毕,异步线程在工作结束后会主动调用我们提供的回调方法,并在回调 方法中做相应的处理。

 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace 异步调用实现方法汇总4
  8. {
  9.     /// <summary>
  10.     /// 异步调用方法总结:
  11.     /// 在调用BeginInvoke时只要提供了回调方法,那么主线程就不必要再等待异步线程工作完毕,
  12.     /// 异步线程在工作结束后会主动调用我们提供的回调方法,并在回调方法中做相应的处理,例如显示异步调用的结果。
  13.     /// </summary>
  14.     class Program
  15.     {
  16.         public delegate void PrintDelegate(string s);
  17.         static void Main(string[] args)
  18.         {
  19.             PrintDelegate printDelegate = Print;
  20.             Console.WriteLine("主线程.");
  21.             printDelegate.BeginInvoke("Hello world.", PrintComeplete, printDelegate);
  22.             Console.WriteLine("主线程继续执行...");
  23.  
  24.             Console.WriteLine("Press any key to continue...");
  25.             Console.ReadKey(true);
  26.         }
  27.         public static void Print(string s)
  28.         { 
  29.             Console.WriteLine("当前线程:"+s);
  30.             Thread.Sleep(5000);
  31.         }
  32.         //回调方法要求
  33.         //1.返回类型为void
  34.         //2.只有一个参数IAsyncResult
  35.         public static void PrintComeplete(IAsyncResult result)
  36.         {
  37.             (result.AsyncState as PrintDelegate).EndInvoke(result);
  38.             Console.WriteLine("当前线程结束." + result.AsyncState.ToString());
  39.         }
  40.     }
  41. }

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:.NET回调异步编程 | Bruce's Blog

发表评论

留言无头像?