c#实现异步处理(使用委托)
C#提供了异步方法调用的功能,先创建一个委托,该委托的签名要与需要异步执行的方法定义相匹配。还是以代码来说明。
委托的声明:
public delegate string AsyncDelegateGetPage( Uri uri , out string url );
调用方代码:
AsyncCallback callback = new AsyncCallback( ProcessPage ); //回调函数声明
AsyncDelegateGetPage ad = new AsyncDelegateGetPage( GetPageSource );//实例化委托类型
IAsyncResult ar = ad.BeginInvoke( this.ObtainWork() ,out url, callback , ad );//开始调用
ar.AsyncWaitHandle.WaitOne();//阻塞主线程,直到异步完成,用于多线程同步,一般可以不需要。
BeginInvoke方法为开始异步调用,其参数为动态的,依据委托的签名。上面的情况,参数为:Uri , out url,回调函数实例(可为null),委托实例(可为null)。即前面的几个参数为委托方法的参数,后面2个分别是回调函数实例和委托实例。参数委托 实例用于将该实例传递到回调函数中。注意回调函数的必须为void ,并且参数为IAsyncResult 类型。
委托的方法代码:
public String GetPageSource( Uri uri , out string url ){
url = uri.ToString();
return this.GetPageSource( uri );
}
回调函数代码:
void ProcessPage( IAsyncResult ar ){
AsyncDelegateGetPage andl = (AsyncDelegateGetPage)ar.AsyncState;
string url;
string source = andl.EndInvoke( out url, ar );
}
委托类型的EndInvoke方法,参数为异步结果,IAsyncResult类型。执行该方法后,返回异步调用的结果。
以上是针对有回调函数的情况。

浙公网安备 33010602011771号