从任务并行库更新ProgressBar UI对象

had*_*teo 4 c# winforms task-parallel-library c#-4.0

基本上我想在FormMain(WindowsForm)上更新ProgressBar UI对象.我使用的是.NET 4.0

以下是Form1.Designer.cs中的代码

namespace ProgressBarApp
{
    public partial class Form1 : Form
    {         
        private System.Windows.Forms.ProgressBar curProgressBar;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CustomProcess theProcess = new CustomProcess();
            theProcess.Process();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是CustomProcess.cs的定义

namespace ProgressBarApp
{
    class CustomProcess
    {
        public void Process()
        {
            for (int i = 0; i < 10; i++)
            {
                Task ProcessATask = Task.Factory.StartNew(() =>
                    {
                        Thread.Sleep(1000); // simulating a process
                    }
                 );

                Task UpdateProgressBar = ProcessATask.ContinueWith((antecedent) =>
                    { 
                        // how do i update the progress bar object at UI here ?
                    }
                 );
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

svi*_*ick 6

你可以SynchronizationContext用来做这件事.要将其用于a Task,您需要创建一个TaskScheduler,您可以通过调用TaskScheduler.FromCurrentSynchronizationContext:

Task UpdateProgressBar = ProcessATask.ContinueWith(antecedent =>
    { 
        // you can update the progress bar object here
    }, TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)

只有Process()直接从UI线程调用时,这才有效.