Welcome

首页 / 软件开发 / .NET编程技术 / 什么是.Net的异步机制(异步Stream读写) - step 4

什么是.Net的异步机制(异步Stream读写) - step 42011-12-05 博客园 Andy Huang异步的Stream读/写操作

下面是继承于System.IO.Stream的类

System.IO.Stream  Microsoft.JScript.COMCharStream  System.IO.BufferedStream  System.IO.FileStream  System.IO.MemoryStream  System.IO.UnmanagedMemoryStream  System.Security.Cryptography.CryptoStream  System.Printing.PrintQueueStream  System.IO.Pipes.PipeStream  System.Data.OracleClient.OracleBFile  System.Data.OracleClient.OracleLob  System.IO.Compression.DeflateStream  System.IO.Compression.GZipStream  System.Net.Sockets.NetworkStream  System.Net.Security.AuthenticatedStream
在System.IO.Stream中提供了异步的读/写(Read/Write)行为,上面继承于System.IO.Stream的类都具有同样的异步操作行为.在.Net Framework框架中,微软设计师使用Begin+同步方法名 / End+同步方法名来设计异步方法的规则,基本上我们在微软MSDN看到的 BeginXXX + EndXXX都是异步的方法,并且当我们在某个类中看到BeginInvoke / EndInvoke,都是微软提供的最原始的异步方法.在System.IO.Stream类中表现为BeginRead+EndRead / BeginWrite/EndWrite.

我们来看一个例子,FileStream(System.IO),Read / BeginRead+EndRead,读取文件内容,开始我们使用同步方法.

同步调用

Code1.1

1static class Program2  {3    static string path = @"c:file.txt";//确保你本地有这个文件4    const int bufferSize = 5;//演示,一次只读取5 byte5    static void Main()6    {7      FileStream fs = new FileStream(path, FileMode.Open,8FileAccess.Read, FileShare.Read, 20480, false);//同步调用false9      using (fs)//使用using来释放FileStream资源10      {11        byte[] data = new byte[bufferSize];12        StringBuilder sb = new StringBuilder(500);13        int byteReads;14        do// 不断循环,直到读取完毕15        {16          byteReads = fs.Read(data, 0, data.Length);17          sb.Append(Encoding.ASCII.GetString(data, 0, byteReads));18        } while (byteReads > 0);19        Console.WriteLine(sb.ToString());//输出到工作台2021      }//自动清除对象资源,隐式调用fs.Close();22      Console.ReadLine();// 让黑屏等待,不会直接关闭..23    }24  }