Mis*_*ssy 3 c# asynchronous async-await
我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
任何帮助,建议或建议将不胜感激.
只是将您的方法标记为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;
}
Run Code Online (Sandbox Code Playgroud)
这将产生UI线程并允许重绘标签.
PS.编译器应该使用您的初始代码发出警告,因为您有一个async不使用的方法await.
| 归档时间: |
|
| 查看次数: |
673 次 |
| 最近记录: |