APM(Asynchronous Programming Modle)的3种模式
出自CLR via C# ch23
//—-Wait until done
定义了FileOptions.Asynchronous,才能调用FileStream.BeignRead(),否则请调用FileStream.Read
如果定义了FileOptions.Asynchronous,又调用Read,FileStream会启动一个工作线程来操作文件,
并Sleep调用线程,知道工作线程完成.
FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)
Byte[] data = new Byte[100];
IAsyncResult ar = fs.BrginRead(data, 0, data.Length, null, null);
//Suspend this thread until the asynchronous operation completes
Int32 bytes = fs.EndRead(ar);
fs.Close();
//—-Polling
FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)
Byte[] data = new Byte[100];
IAsyncResult ar = fs.BrginRead(data, 0, data.Length, null, null);
while(!ar.IsComplete)
{
Thread.Sleep(10);
}
Int32 bytes = fs.EndRead(ar);
fs.Close();
//—-Callback
FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)
Byte[] data = new Byte[100];
fs.BrginRead(data, 0, data.Length, ReadIsDone, fs);
…
private static void ReadIsDone(IAsyncResult ar)
{
FileStream fs = (FileStream)ar.AyncState;
Int32 bytes = fs.EndRead(ar);
fs.Close();
}
也可以使用匿名方法写成:
FileStream fs = new FileStream(@”c:\boot.ini”, FileMode.Open, FileAccess)
Byte[] data = new Byte[100];
IAsyncResult ar = fs.BrginRead(data, 0, data.Length,
delegate(IAsyncResult ar)
{
Int32 bytes = fs.EndRead(ar);
fs.Close();
}
, null);
这样写的好处是匿名方法可以访问所有的局部变量(data, fs),所以不用把fs传递给它.
