使用.NET异步委托
来源:互联网 发布:中世纪2原版优化10 编辑:程序博客网 时间:2024/05/20 06:28
异步委托通过编译器提供的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
- 使用.NET异步委托
- vb.net的异步读写数据流(使用线程、委托)
- vb.net的异步读写数据流(使用线程、委托)
- 异步委托的使用
- c#使用异步委托
- C# 异步委托使用
- c#异步委托委托的使用
- C#委托的异步使用
- 使用委托进行异步编程
- C#委托的异步使用
- C#异步委托的使用
- 异步委托---使用BeginInvoke,EndInvoke
- ASP.NET 委托,异步调用例子
- ASP.NET 委托 事件 异步调用
- 笔记7:vb.net的异步读写数据流(使用线程、委托)
- C#异步委托之委托使用的时机浅析
- c#使用委托实现异步调用
- c#使用委托实现异步调用
- 字符编码的使用和转换
- 计算机的设计(1)
- 硬盘
- 使用HttpHandlers异步传输图片
- 一个源码网站
- 使用.NET异步委托
- 关于MD5
- 磁盘
- 谈谈手机软件
- Python vs C#
- 小罗”巧克力风靡瑞士
- 巴西队不喜“团队之星”
- 2006年世界杯在线播放
- MyEclipse+struts+Hibernate配置开发