且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更新 UI 线程而无需继续执行任务

更新时间:2023-02-09 17:14:03

您可以使用 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);
    }
}