3
我有一个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;
}
任何帮助,意见或建议将不胜感激。
OMG!有效!!!我很激动,我终于开始理解这种异步的东西。谢谢你,谢谢你,谢谢你!!!! – Missy