更新 UI 线程而无需继续执行任务 [英] Updating the UI Thread without a task to continue on

查看:57
本文介绍了更新 UI 线程而无需继续执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个任务,它启动一个方法并循环给定的次数.每个循环我都想模拟一些正在完成的工作 (Thread.Sleep) 并在之后更新 UI.我目前知道更新 UI 线程的唯一方法是任务继续.我的问题是在方法中,我没有任务可以继续.

I currently have a Task that starts a method and loops a given amount of times. Each loop I want to simulate some work being done (Thread.Sleep) and update the UI afterwards. The only way I currently know to update the UI thread is with task continuation. My problem here is that in the method, I dont have a task to continue on.

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 工作?提前致谢.

Is there a way to refactor this code to work using only the TPL? Thanks in advance.

推荐答案

您可以使用 IProgress 将进度报告回 UI 线程.

You can use IProgress<T> to report progress back to the UI thread.

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

这篇关于更新 UI 线程而无需继续执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆