2017-09-30 36 views
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; 
} 

任何帮助,意见或建议将不胜感激。

回答

4

只是将您的方法标记为async对执行流程几乎没有影响,因为您不会执行任何执行。

使用ReadLineAsync而不是ReadLineWriteLineAsync代替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。编译器应该用您的初始代码提出警告,因为您有一个不使用awaitasync方法。 OMG!

+0

OMG!有效!!!我很激动,我终于开始理解这种异步的东西。谢谢你,谢谢你,谢谢你!!!! – Missy