我正在编写一些代码来学习新的 c# 异步设计模式。所以我想写一个小的windows窗体程序来计算文本文件的行数并显示阅读进度。
为了避免磁盘交换,我将文件读入 MemoryStream,然后构建一个 StreamReader 以逐行读取文本并计数。
问题是我无法正确更新进度条。我读了一个文件,但总是缺少字节,所以进度条没有完全填满。
需要一只手或一个想法来实现这一点。谢谢
public async Task Processfile(string fname)
{
MemoryStream m;
fname.File2MemoryStream(out m); // custom extension which read file into
// MemoryStream
int flen = (int)m.Length; // store File length
string line = string.Empty; // used later to read lines from streamreader
int linelen = 0; // store current line bytes
int readed = 0; // total bytes read
progressBar1.Minimum = 0; // progressbar bound to winforms ui
progressBar1.Maximum = flen;
using (StreamReader sr = new StreamReader(m)) // build streamreader from ms
{
while ( ! sr.EndOfStream ) // tried ( line = await sr.ReadLineAsync() ) != null
{
line = await sr.ReadLineAsync();
await Task.Run(() =>
{
linelen = Encoding.UTF8.GetBytes(line).Length; // get & update
readed += linelen; // bytes read
// custom function
Report(new Tuple<int, int>(flen, readed)); // implements Iprogress
// to feed progress bar
});
}
}
m.Close(); // releases MemoryStream
m = null;
}