//异步io的一个例子, 不明白???? 异步为什么那样复杂,以及异步io的步骤。using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Threading; namespace _5_10{ public class filereader { const string path = "E:\\1.txt"; public void synccall() //同步的 { FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read,1024,false); int x = 0; while ((x = fs.ReadByte())!= -1) { } fs.Close(); Console.WriteLine("synchro open finished "+DateTime.Now); } public void asynccall() //异步的 { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true); worddocstate state = new worddocstate(); state.fs = fs; state.content = new byte[fs.Length]; state.resetevent = new AutoResetEvent(false); AsyncCallback readdoccallback = new AsyncCallback(ReadDocCallback); fs.BeginRead(state.content,0,(int)state.fs.Length,ReadDocCallback,state); state.resetevent.WaitOne(); Console.WriteLine("async open finished "+DateTime.Now); } private void ReadDocCallback(IAsyncResult asyncresult) { worddocstate state = (worddocstate)asyncresult.AsyncState; FileStream stream = state.fs; int bytesread = stream.EndRead(asyncresult); stream.Close(); state.resetevent.Set(); } public class worddocstate { public FileStream fs; public byte[] content; public AutoResetEvent resetevent; } static void Main(string[] args) { filereader fr = new filereader(); fr.synccall(); fr.asynccall(); } }}

评论