異步讀取文件,讀取完成之後觸發事件,通知主線程。主線程與讀取文件的線程互相獨立。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
namespace ExToDB.FileTransfer
{
/// <summary>
/// 異步讀取文件
/// </summary>
public class AsyncProcessor
{
private Stream inputStream;
public Stream InputStream
{
get { return inputStream; }
set { inputStream = value; }
}
// 每次讀取塊的大小
private int bufferSize = 2048;
public event ReturnEndEvent IsReturnEvent;
protected void OnIsReturnEvent()
{
if (IsReturnEvent != null)
IsReturnEvent(this, new ReturnEndReadEventargs(true));
}
public int BufferSize
{
get { return bufferSize; }
set { bufferSize = value; }
}
// 容納接收數據的緩存
private byte[] buffer;
public AsyncProcessor(string fileName)
{
buffer = new byte[bufferSize];
// 打開文件,指定參數為true以提供對異步操作的支持
inputStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, true);
}
/// <summary>
/// 開始讀取
/// </sum