New to Telerik UI for WinForms? Download free 30-day trial

Update RadProgressBar while a Long-Lasting Operation is Ongoing

Environment

Product Version Product Author
2019.3.917 RadProgressBar for WinForms Desislava Yordanova

Description

Many users face a similar issue: once a time-consuming operation is started, RadProgressBar does not update immediately and literally freezes. Such cases occur when the long-running operation is executed on the same thread as the RadProgressBar update process: the primary UI Thread. The operation does not allow the form to update its UI and as a result the control does not perform any visual updates.

Solution

One obvious solution is to start the time-consuming operation in a new thread. A sample approach to achieve this is by using a BackgroundWorker.

The BackgroundWorker.ProgressChanged event is used to update the value of RadProgressBar:

update-progressbar-while-a-long-lasting-operation-is-ongoing001

Update progress


private BackgroundWorker myBackgroundWorker;

public RadForm1()
{
    InitializeComponent();
    myBackgroundWorker = new BackgroundWorker();
    myBackgroundWorker.WorkerReportsProgress = true;
    myBackgroundWorker.WorkerSupportsCancellation = true;
    myBackgroundWorker.DoWork += myBackgroundWorker1_DoWork;
    myBackgroundWorker.RunWorkerCompleted += myBackgroundWorker1_RunWorkerCompleted;
    myBackgroundWorker.ProgressChanged += myBackgroundWorker1_ProgressChanged;
}

private void radButton1_Click(object sender, EventArgs e)
{
    if (!myBackgroundWorker.IsBusy)
    {
        myBackgroundWorker.RunWorkerAsync();
        this.radButton1.Enabled = false;
        this.radProgressBar1.Maximum = 100;
    }
}

 int count = 0;

private void myBackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    while (count < 100)
    {
        Thread.Sleep(200);
        worker.ReportProgress(count, "");
        count = count + 1;
    }
}

private void myBackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    this.radButton1.Enabled = true;
    this.radProgressBar1.Text = "100%";
    this.radProgressBar1.Value1 = this.radProgressBar1.Maximum;
}

private void myBackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.radProgressBar1.Value1 = e.ProgressPercentage;
    this.radProgressBar1.Text = this.radProgressBar1.Value1 + "%";
    this.radProgressBar1.ProgressBarElement.UpdateLayout();
    this.radProgressBar1.Refresh();
}

In this article