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

标签 c# winforms c#-4.0 task-parallel-library

基本上我想更新 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();
        }
    }
}

这里是 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 ?
                    }
                 );
            }
        }
    }
}

最佳答案

您可以使用 SynchronizationContext去做这个。要将它用于Task,您需要创建一个TaskScheduler,您可以通过调用TaskScheduler.FromCurrentSynchronizationContext 来完成。 :

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

只有当您直接从 UI 线程调用 Process() 时,这才会起作用。

关于c# - 从任务并行库更新 ProgressBar UI 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13946839/

相关文章:

c# - 从非静态方法构建静态委托(delegate)

c# - 处理未读邮件时出现问题并在处理后将其标记为已读

c# - 从 TreeView 节点中删除子节点时出现空异常

c# - 获得 Trace.indent 和 trace.unindent 等价物的 log4net 模式是什么

c# - Xamarin.Forms 2.5.0 和上下文

wpf - winforms,WPF和metro之间的区别?

c# - 在后台进行 UI 工作

c#-4.0 - 从碎片化的 MP4 "mdat"原子重建 MP4 文件?

c# - 静态构造函数如何工作?

c# - 无法加载文件或程序集 'System, Version=4.0.0.0, Culture=neutral' 或其依赖项之一