您的位置:首页 > 职场人生

黑马程序员之C#学习笔记:使用Stream.BeginRead方法读取FileStream的流内容

2012-11-14 20:37 926 查看
----------------------------------2345王牌技术员联盟2345王牌技术员联盟、期待与您交流!---------------------------

BeginRead在一些流中的实现和Read完全相同,比如MemoryStream;而在FileStream和NetwordStream中BeginRead就是实实在在的异步操作了。using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Threading;

namespace UseBeginRead

class Program

{

//定义异步读取状态类

class AsyncState

{

public FileStream FS { get; set; }

public byte[] Buffer { get; set; }

public ManualResetEvent EvtHandle { get; set; }

}

static int bufferSize = 512;

static void Main(string[] args)

{

string filePath = "d:\\test.txt";

//以只读方式打开文件流

using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))

{

var buffer = new byte[bufferSize];

//构造BeginRead需要传递的状态

var asyncState = new AsyncState { FS = fileStream, Buffer = buffer ,EvtHandle = new ManualResetEvent(false)};

//异步读取

AsyncResult asyncResult = fileStream.BeginRead(buffer, 0, bufferSize, new AsyncCallback(AsyncReadCallback), asyncState);

//阻塞当前线程直到读取完毕发出信号

asyncState.EvtHandle.WaitOne();

Console.WriteLine();

Console.WriteLine("read complete");

Console.Read();

}

}

//异步读取回调处理方法

public static void AsyncReadCallback(IAsyncResult asyncResult)

{

var asyncState = (AsyncState)asyncResult.AsyncState;

int readCn = asyncState.FS.EndRead(asyncResult);

//判断是否读到内容

if (readCn > 0)

{

byte[] buffer;

if (readCn == bufferSize) buffer = asyncState.Buffer;

else

{

buffer = new byte[readCn];

Array.Copy(asyncState.Buffer, 0, buffer, 0, readCn);

}

//输出读取内容值

string readContent = Encoding.UTF8.GetString(buffer);

Console.Write(readContent);

}

if (readCn < bufferSize)

{

asyncState.EvtHandle.Set();

}

else {

Array.Clear(asyncState.Buffer, 0, bufferSize);

//再次执行异步读取操作

asyncState.FS.BeginRead(asyncState.Buffer, 0, bufferSize, new AsyncCallback(AsyncReadCallback), asyncState);

}

}

}

---------------------------------------------------
2345王牌技术员联盟2345王牌技术员联盟、期待与您交流!---------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐