我有一个C#WPF程序,它打开一个文件,逐行读取,操作每一行然后将该行写入另一个文件。那部分工作正常。我想添加一些进度报告,因此我将方法设为异步并使用等待进度报告。进度报告非常简单 - 只需更新屏幕上的标签即可。这是我的代码:
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;
}
非常感谢任何帮助,建议或建议。
答案 0 :(得分:5)
将方法标记为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
。