【问题标题】:Updating the UI Thread without a task to continue on [duplicate]在没有任务的情况下更新 UI 线程以继续 [重复]
【发布时间】:2018-11-13 18:42:48
【问题描述】:

我目前有一个启动方法并循环给定次数的任务。每个循环我都想模拟一些正在完成的工作(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 工作?提前致谢。

【问题讨论】:

    标签: c# multithreading task-parallel-library


    【解决方案1】:

    您可以使用 IProgress&lt;T&gt; 将进度报告回 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 2019-05-22
      • 2019-07-22
      • 1970-01-01
      相关资源
      最近更新 更多