在没有任务继续的情况下更新UI线程

时间:2018-11-13 18:42:49

标签: c# multithreading task-parallel-library

我目前有一个Task,它启动一个方法并循环给定的时间。每个循环我都想模拟一些正在完成的工作(Thread.Sleep),然后再更新UI。我当前知道的更新UI线程的唯一方法是任务继续。我的问题是在该方法中,我没有任务要继续。

private void StartButton_Click(object sender, RoutedEventArgs e)
    {
        this.pbStatus.Value = 0;
        Task.Run(() => StartProcess(100));

        //Show message box to demonstrate that StartProcess()
        //is running asynchronously
        MessageBox.Show("Called after async process started.");
    }

    // Called Asynchronously
    private void StartProcess(int max)
    {
        for (int i = 0; i <= max; i++)
        {
            //Do some work
            Thread.Sleep(10);

            //How to correctly update UI?
            this.lblOutput.Text = i.ToString();
            this.pbStatus.Value = i;
        }
    }

是否有一种方法可以重构此代码以仅使用TPL来工作?预先感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用IProgress<T>向UI线程报告进度。

private void StartButton_Click(object sender, RoutedEventArgs e)
{
    this.pbStatus.Value = 0;

    //Setup the progress reporting
    var progress = new Progress<int>(i =>
    {
        this.lblOutput.Text = i.ToString();
        this.pbStatus.Value = i;
    });
    Task.Run(() => StartProcess(100, progress));

    //Show message box to demonstrate that StartProcess()
    //is running asynchronously
    MessageBox.Show("Called after async process started.");
}

// Called Asynchronously
private void StartProcess(int max, IProgress<int> progress)
{
    for (int i = 0; i <= max; i++)
    {
        //Do some work
        Thread.Sleep(10);

        //Report your progress
        progress.Report(i);
    }
}
相关问题