关闭

使用.NET异步委托

1532人阅读 评论(0) 收藏 举报

异步委托通过编译器提供的BeginInvoke方法与EndInvoke方法对delegate进行异步的调用.
被调用方法将在系统线程池中运行,并且被调用方没有必要为异步执行行为提供附加的代码支持.
当异步执行结束时,通过调用回调函数发出通知.

如果委托在异步执行中抛出了异常,那么在调用EndInvoke时才会被捕获到

MSDN页面:
ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpguide/html/cpovrasynchronousprogrammingoverview.htm
ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpguide/html/cpconasynchronousdesignpatternoverview.htm


以下为示例:

using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace AsyncDele
{
 // 定义被调用方法的delegate
 public delegate bool Workdele( int source, out int ithreadid );

 // 被调用方,封装被调用方法
 class Worker
 {
  public bool Dowork( int source, out int ithreadid )
  {
   ithreadid = AppDomain.GetCurrentThreadId();
   Console.WriteLine( "my work starting in thread:{0}...", ithreadid );

   Thread.Sleep( 5000 );

   Console.WriteLine( "my work ended in thread:{0}", ithreadid );
   return (source % 2) == 0;
  }
 }

 // 封装完成回调方法
 class ProcessWorkResult
 {
  public void CallbackMethod( IAsyncResult ar )
  {
   Console.WriteLine( "callback int thread:{0}", AppDomain.GetCurrentThreadId() );
   Workdele wd = (Workdele)((AsyncResult)ar).AsyncDelegate;
   int ithreadid;
   bool bret = wd.EndInvoke( out ithreadid, ar );
   Console.WriteLine( "callback end: ithreadid={0} bret={1}", ithreadid, bret );
  }
 }

 // 调用方
 class AsyncWorker
 {
  public void Dowork( int source )
  {
   Worker worker = new Worker();
   Workdele wd = new Workdele( worker.Dowork );

   ProcessWorkResult wr = new ProcessWorkResult();
   AsyncCallback cb = new AsyncCallback( wr.CallbackMethod );

   Console.WriteLine( "begin aync invoke..." );
   int ithreadid;
   IAsyncResult ar = wd.BeginInvoke( source, out ithreadid, cb, (object)source );
   Thread.Sleep( 0 );
   Console.WriteLine( "async invoke return." );
  }
 }

 class Class1
 {
  static void Main(string[] args)
  {
   Console.WriteLine( "start" );

   AsyncWorker worker = new AsyncWorker();
   worker.Dowork( 13 );
   
   Console.WriteLine( "press enter to exit." );
   Console.ReadLine();
  }
 }
}

执行结果如下:
start
begin aync invoke...
my work starting in thread:2760...
async invoke return.
press enter to exit.
my work ended in thread:2760
callback int thread:2760
callback end: ithreadid=2760 bret=False

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7141次
    • 积分:115
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档