I have a C# WPF program that opens a file, reads it line by line, manipulates each line then writes the line out to another file. That part worked fine. I wanted to add some progress reporting so I made the methods async
and used await
with progress reporting. The progress reporting is super simple - just update a label on the screen. Here is my code:
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;
}
But the progress reporting is not working.
Any help, advice or suggestions would be greatly appreciated.