等待/异步阻止UI

时间:2019-05-25 17:29:49

标签: c#

我有一个非常简单的应用程序,它实际上只是一个更大的模块,在其中我必须处理文本文档的所有段落。我已经编写了一个异步方法来允许进度报告,而不是冻结UI,但是这些都不起作用。进度条仅在末尾填充,并且在执行过程中UI被阻止。

我尝试了async / await和BackgroundWorker方法,都没有用。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public async Task<string> ReadTextFile()
    {
        string result = null;

        using (StreamReader reader = File.OpenText(@"C:\Users\Junior\Desktop\asynctest.txt"))
        {
            result = await reader.ReadToEndAsync();
        }

        return result;
    }

    public string[] CreateParagraphs(string text)
    {
        string[] result;

        result = text.Split(new string[] { "\n", "\r", "\r\n" },  StringSplitOptions.None);

        return result;
    }

    public List<string> ReplaceGestures(string[] paragraphs, IProgress<int> progress)
    {
        List<string> result = new List<string>();

        for(int i=0; i < paragraphs.Length; i++)
        {
            paragraphs[i] = paragraphs[i].Replace("+", "(*)");

            if (progress != null && (i % 10 == 0))
                progress.Report(i);
        }

        return result;
    }

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Info.Text = "Reading file...";

        string text = await ReadTextFile();

        Info.Text = "Creating paragraphs...";

        string[] paragraphs = await Task.Run(() => CreateParagraphs(text));

        Info.Text = "Replacing gestures....";

        Bar.Maximum = paragraphs.Length;

        var progress = new Progress<int>(percent =>
        {
            Bar.Value = percent; 
        });

        List<string> paragraphsWithGestures = await Task.Run(() => ReplaceGestures(paragraphs, progress));

        Info.Text = "Done.";
    }
}

我希望这段代码能以10次迭代间隔更新进度条。

0 个答案:

没有答案