接下來看這三個事件的處理程序。每一個事件都有各自的 EventArgs 參數類型,都很簡單就不多說了
第一個 BackgroundWorker_DoWork 方法寫得我有些郁悶。我在方法裡取文件長度,先是直接取 StreamReader.BaseStream.Length 或 FileInfo.Length ,結果卻導致很多文件讀不到 100% 就結束了,不得已改成先把整個文件讀一次得到字符串的長度。這樣的方法當然性能不好了,主要是因為自己對 IO 一直就不夠清楚,等下一個主題重新認識下 IO 再回頭過來改吧。也望有經驗的朋友賜教,感激不盡
/**//// <summary>
/// DoWork event process method
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
long length;
using (StreamReader sr = new StreamReader(m_FilePath))
{
// Get file length
length = sr.ReadToEnd().Length;
}
using (StreamReader sr = new StreamReader(m_FilePath))
{
long onePercentOfLength = length / 100;
long currentPosition = 0;
int i = 0;
while (!sr.EndOfStream)
{
sr.Read();
currentPosition ++;
// Produce ProcessChanged event in each percent reading
while (currentPosition > onePercentOfLength * i)
{
((BackgroundWorker)sender).ReportProgress(i++);
}
}
// e.Result will be used in RunWorkerCompleted event process method
e.Result = currentPosition;
}
}
BackgroundWorker_ProgressChanged 方法,簡單輸出當前進度
/**//// <summary>
/// ProgressChanged event process method
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Reading percents: " + e.ProgressPercentage + "%");
}