我有一个 C# WPF 程序,它打开一个文件,逐行读取它,操作每一行,然后将该行写入另一个文件。那部分工作得很好。我想添加一些进度报告,因此我将方法设为异步并使用 await 与进度报告。进度报告非常简单 - 只需更新屏幕上的标签即可。这是我的代码:

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;
}

任何帮助、建议或建议将不胜感激。

最佳答案

仅将您的方法标记为 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 线程并允许重新绘制标签。

附注。编译器应该对您的初始代码发出警告,因为您有一个不使用 asyncawait 方法。

关于c# - 异步等待进度报告不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46498581/

10-11 07:20