我有一个 C# WPF 程序,它打开一个文件,逐行读取它,操作每一行,然后将该行写入另一个文件。那部分工作得很好。我想添加一些进度报告,所以我制作了方法
async
并使用 await
进行进度报告。进度报告非常简单 - 只需更新屏幕上的标签即可。这是我的代码:
async void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Select File to Process";
openFileDialog.ShowDialog();
lblWaiting.Content = "Please wait!";
var progress = new Progress<int>(value =>
{
lblWaiting.Content = "Waiting "+ value.ToString();
});
string newFN = await FileProcessor(openFileDialog.FileName, progress);
MessageBox.Show("New File Name " + newFN);
}
static async private Task<string> FileProcessor(string fn, IProgress<int> progress)
{
FileInfo fi = new FileInfo(fn);
string newFN = "C:\temp\text.txt";
int i = 0;
using (StreamWriter sw = new StreamWriter(newFN))
using (StreamReader sr = new StreamReader(fn))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// manipulate the line
i++;
sw.WriteLine(line);
// every 500 lines, report progress
if (i % 500 == 0)
{
progress.Report(i);
}
}
}
return newFN;
}
但是进度报告不起作用。
如有任何帮助、意见或建议,我们将不胜感激。
仅将您的方法标记为
async
对执行流程几乎没有影响,因为您永远不会产生执行。
使用
ReadLineAsync
代替 ReadLine
,使用 WriteLineAsync
代替 WriteLine
:
static async private Task<string> FileProcessor(string fn, IProgress<int> progress)
{
FileInfo fi = new FileInfo(fn);
string newFN = "C:\temp\text.txt";
int i = 0;
using (StreamWriter sw = new StreamWriter(newFN))
using (StreamReader sr = new StreamReader(fn))
{
string line;
while ((line = await sr.ReadLineAsync()) != null)
{
// manipulate the line
i++;
await sw.WriteLineAsync(line);
// every 500 lines, report progress
if (i % 500 == 0)
{
progress.Report(i);
}
}
}
return newFN;
}
这将产生 UI 线程并允许重新绘制标签。
PS。编译器应该对您的初始代码发出警告,因为您有一个不使用
async
的 await
方法。