本文转自:http://www.cnblogs.com/jiangnii/archive/2007/08/05/843872.aspx
.NET Framework 为异步操作提供了两种设计模式:使用 IAsyncResult 对象的异步操作与使用事件的异步操作。先来学习前者
概述
IAsyncResult 异步设计模式通过名为 BeginOperationName 和 EndOperationName 的两个方法来实现原同步方法的异步调用,如 FileStream 类提供了 <link tabindex="0" keywords="M:System.IO.FileStream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)"> 和 <link tabindex="0" keywords="M:System.IO.FileStream.EndRead(System.IAsyncResult)"> 方法来从文件异步读取字节,它们是 <link tabindex="0" keywords="M:System.IO.FileStream.Read(System.Byte[],System.Int32,System.Int32)"> 方法的异步版本
Begin 方法包含同步方法签名中的任何参数,此外还包含另外两个参数:一个AsyncCallback 委托和一个用户定义的状态对象。委托用来调用回调方法,状态对象是用来向回调方法传递状态信息。该方法返回一个实现 IAsyncResult 接口的对象
End 方法用于结束异步操作并返回结果,因此包含同步方法签名中的 ref 和 out 参数,返回值类型也与同步方法相同。该方法还包括一个 IAsyncResult 参数,用于获取异步操作是否完成的信息,当然在使用时就必须传入对应的 Begin 方法返回的对象实例
开始异步操作后如果要阻止应用程序,可以直接调用 End 方法,这会阻止应用程序直到异步操作完成后再继续执行。也可以使用 IAsyncResult的 AsyncWaitHandle属性,调用其中的WaitOne等方法来阻塞线程。这两种方法的区别不大,只是前者必须一直等待而后者可以设置等待超时
如果不阻止应用程序,则可以通过轮循 IAsyncResult的 IsCompleted状态来判断操作是否完成,或使用 AsyncCallback 委托来结束异步操作。AsyncCallback 委托包含一个 IAsyncResult的签名,回调方法内部再调用 End 方法来获取操作执行结果
尝试
先来熟悉一下今天的主角,IAsyncResult 接口
publicinterface
IAsyncResult


{

objectAsyncState
{get;}

WaitHandleAsyncWaitHandle
{get;}

boolCompletedSynchronously
{get;}

boolIsCompleted
{get;}
}
我用一个 AsyncDemo 类作为异步方法的提供者,后面的程序都会调用它。内部很简单,构造函数接收一个字符串作为 name ,Run 方法输出 "My name is " + name ,而异步方法直接用委托的 BeginInvoke 和 EndInvoke 方法实现
publicclass
AsyncDemo


{
//Useinasynchronousmethods
privatedelegatestringrunDelegate();

privatestringm_Name;
privaterunDelegatem_Delegate;

publicAsyncDemo(stringname)


{
m_Name=name;
m_Delegate=newrunDelegate(Run);
}


/**////<summary>
///Synchronousmethod
///</summary>
///<returns></returns>
publicstringRun()


{
return"Mynameis"+m_Name;
}


/**////<summary>
///Asynchronousbeginmethod
///</summary>
///<paramname="callBack"></param>
///<paramname="stateObject"></param>
///<returns></returns>
publicIAsyncResultBeginRun(AsyncCallbackcallBack,ObjectstateObject)


{
try


{
returnm_Delegate.BeginInvoke(callBack,stateObject);
}
catch(Exceptione)


{
//Hideinsidemethodinvokingstack
throwe;
}
}


/**////<summary>
///Asynchronousendmethod
///</summary>
///<paramname="ar"></param>
///<returns></returns>
publicstringEndRun(IAsyncResultar)


{
if(ar==null)
thrownewNullReferenceException("Arggumentarcan'tbenull");

try


{
returnm_Delegate.EndInvoke(ar);
}
catch(Exceptione)


{
//Hideinsidemethodinvokingstack
throwe;
}
}
}
首先是 Begin 之后直接调用 End 方法,当然中间也可以做其他的操作
class
AsyncTest


{
staticvoidMain(string[]args)


{
AsyncDemodemo=newAsyncDemo("jiangnii");

//Executebeginmethod
IAsyncResultar=demo.BeginRun(null,null);

//Youcandootherthingshere

//Useendmethodtoblockthreaduntiltheoperationiscomplete
stringdemoName=demo.EndRun(ar);
Console.WriteLine(demoName);
}
}
也可以用 IAsyncResult的 AsyncWaitHandle属性,我在这里设置为1秒超时
class
AsyncTest


{
staticvoidMain(string[]args)


{
AsyncDemodemo=newAsyncDemo("jiangnii");

//Executebeginmethod
IAsyncResultar=demo.BeginRun(null,null);

//Youcandootherthingshere

//UseAsyncWaitHandle.WaitOnemethodtoblockthreadfor1secondatmost
ar.AsyncWaitHandle.WaitOne(1000,false);

if(ar.IsCompleted)


{
//Stillneeduseendmethodtogetresult,butthistimeitwillreturnimmediately
stringdemoName=demo.EndRun(ar);
Console.WriteLine(demoName);
}
else


{
Console.WriteLine("Sorry,can'tgetdemoName,thetimeisover");
}
}
}
不中断的轮循,每次循环输出一个 "."
class
AsyncTest


{
staticvoidMain(string[]args)


{
AsyncDemodemo=newAsyncDemo("jiangnii");

//Executebeginmethod
IAsyncResultar=demo.BeginRun(null,null);

Console.Write("Waiting..");
while(!ar.IsCompleted)


{
Console.Write(".");
//Youcandootherthingshere
}
Console.WriteLine();

//Stillneeduseendmethodtogetresult,butthistimeitwillreturnimmediately
stringdemoName=demo.EndRun(ar);
Console.WriteLine(demoName);
}
}
最后是使用回调方法并加上状态对象,状态对象被作为 IAsyncResult 参数的AsyncState 属性被传给回调方法。回调方法执行前不能让主线程退出,我这里只是简单的让其休眠了1秒。另一个与之前不同的地方是 AsyncDemo对象被定义成了类的静态字段,以便回调方法使用
class
AsyncTest


{
staticAsyncDemodemo=newAsyncDemo("jiangnii");

staticvoidMain(string[]args)


{
//Stateobject
boolstate=false;

//Executebeginmethod
IAsyncResultar=demo.BeginRun(newAsyncCallback(outPut),state);

//Youcandootherthinshere

//Waituntilcallbackfinished
System.Threading.Thread.Sleep(1000);
}

//Callbackmethod
staticvoidoutPut(IAsyncResultar)


{
boolstate=(bool)ar.AsyncState;
stringdemoName=demo.EndRun(ar);

if(state)


{
Console.WriteLine(demoName);
}
else


{
Console.WriteLine(demoName+",isn'tit?");
}
}
}
其他
对于一个已经实现了 BeginOperationName 和 EndOperationName 方法的对象,我们可以直接用上述方式调用,但对于只有同步方法的对象,我们要对其进行异步调用也不需要增加对应的异步方法,而只需定义一个委托并使用其 BeginInvoke 和 EndInvoke 方法就可以了
评论