人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

June 28, 2006

APM(Asynchronous Programming Modle)的3种模式

Filed under: .NET

出自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传递给它.

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/06/28/p116/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham