Updating the ProgressBar UI Object from the Parallel Task Library

Basically, I would like to update the ProgressBar interface object to FormMain (WindowsForm). I am using .NET 4.0

Here is the code in 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(); } } } 

Here is the definition of 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 ? } ); } } } } 
+4
source share
2 answers

You can use SynchronizationContext for this. To use it for Task , you need to create a TaskScheduler , which you can do by calling TaskScheduler.FromCurrentSynchronizationContext :

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

This will only work if you call Process() directly from the user interface thread.

+6
source

How about using System.Reactive.Linq :

[UPDATE]

 using System.Reactive.Linq; namespace WindowsFormsApplication6 { 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(); var x = Observable.FromEventPattern(theProcess, "TaskCompleted"); curProgressBar.Maximum = 4; x.Subscribe((a) => { curProgressBar.Value = ((CustomProcess)a.Sender).Counter; }); theProcess.Process(); } } class CustomProcess { public int Counter { get; set; } public event EventHandler TaskCompleted = OnTaskCompleted; private static void OnTaskCompleted(object sender, EventArgs e) { ((CustomProcess)sender).Counter++; } public void Process() { for (int i = 0; i <= 3; i++) { Task ProcessATask = Task.Factory.StartNew(() => { Thread.Sleep(1000); // simulating a process } ); var awaiter = ProcessATask.GetAwaiter(); awaiter.OnCompleted(() => { TaskCompleted(this, null); }); } } } } 
+4
source

All Articles