Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update ProgressBar UI object from Task Parallel Library

Basically i would like to update ProgressBar UI object on the FormMain (WindowsForm). I am using .NET 4.0

Here are the code in the 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 ?
                    }
                 );
            }
        }
    }
}
like image 669
hadi teo Avatar asked Dec 27 '22 12:12

hadi teo


1 Answers

You can use SynchronizationContext to do this. To use it for a 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 work only if you call Process() directly from the UI thread.

like image 55
svick Avatar answered Jan 04 '23 22:01

svick