异步的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 Program 2 { 3 static string path = @"c:\file.txt";//确保你本地有这个文件 4 const int bufferSize = 5;//演示,一次只读取5 byte 5 static void Main() 6 { 7 FileStream fs = new FileStream(path, FileMode.Open, 8FileAccess.Read, FileShare.Read, 20480, false);//同步调用false 9 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());//输出到工作台 20 21 }//自动清除对象资源,隐式调用fs.Close(); 22 Console.ReadLine();// 让黑屏等待,不会直接关闭.. 23 } 24 }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索微软
, 方法
, stream
, system
, 同步
, filestream
, System.IO
, 异步io
, fs.read方法
异步读取
tfilestream 共享读写、java stream 异步、异步读写、opc 异步读写、异步文件读写,以便于您获取更多的相关知识。