简体   繁体   English

使用TPL异步更新进度条

[英]Updating progress bar asynchronously using TPL

I have the following code here: 我在这里有以下代码:

public class ProcessTaskAsyncExProgress
{
    public int ProgressPercentage { get; set; }

    public string Text { get; set; }
}

public static class ProcessTask
{
    public static async Task<string> Start(IProgress<ProcessTaskAsyncExProgress> progress)
    {
        const int total = 10;
        for (var i = 0; i <= total; i++)
        {
            Thread.Sleep(300);
            if (progress != null)
            {
                var args = new ProcessTaskAsyncExProgress
                {
                    ProgressPercentage = (int)(i / (double)total * 100.0),
                    Text = "processing " + i
                };
                progress.Report(args);
            }
        }
        return "Done";
    }
}

And in Form1.cs 并在Form1.cs中

    private async void button1_Click(object sender, EventArgs e)
    {
        var result = await StartTask();
    }

    private async Task<string> StartTask()
    {
        var progress = new Progress<ProcessTaskAsyncExProgress>();
        progress.ProgressChanged += (s, e) =>
        {
            progressBar1.Value = e.ProgressPercentage;
            listBox1.Items.Add(e.Text);
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        };
        return await ProcessTask.Start(progress);
    }

The problem I'm having is that the progress bar, and listbox doesn't populate while the loop is running. 我遇到的问题是进度条和循环运行时列表框没有填充。 the UI is only updated after the whole loop is completed, and what gets displayed are 10 items in the listview and a 100% progress bar. 仅在整个循环完成后才更新UI,显示的内容是列表视图中的10个项目和100%的进度条。

How should my code be such that the the UI thread isn't hanged? 我的代码应该如何避免UI线程挂起?

Thread.Sleep(300); is a blocking call, it is running on UI thread that's why you are not getting the updates on UI. 是一个阻止调用,它正在UI线程上运行,这就是为什么您无法在UI上获取更新的原因。 You need to use await Task.Delay(300); 您需要使用await Task.Delay(300); instead 代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM