.Net → C# – Windows Form with ProgressBar
This post will deal with showing a ProgressBar with a Windows Forms application to show progress of a long process running in the background. If you have code that will take an abnormal amount of time(more than a few seconds), you don’t want your UI to “hang” because of the long processing. To get around this is to run the long process in a background thread, and update the main UI with progress of where the process is at.
We will be doing this using the BackgroundWorker class. This is probably the easiest way to get background threads up and running quickly.
So first we will have these using statements at the top.
using System; using System.ComponentModel; using System.Threading; using System.Windows.Forms;
Next, we define our BackgroundWorker object.
BackgroundWorker bgw;
public Form1()
{
InitializeComponent();
}
On my form, I have a button to start the process. Here is the Click Event for it…
private void btnStart_Click(object sender, EventArgs e)
{
bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerAsync();
}
In the preceding code, we created a new BackgroundWorker object. We also set the object to allow it to report it’s progress. We then create 3 event handlers for the ProgressChanged, RunWorkerCompleted, and DoWork events. The ProgressChanged event is fired when the progress is changed(like you didn’t see that one coming). The RunWorkerCompleted event is fired when the process has been completed. The DoWork event is the event where your long processing code will go.
The RunWorkerAsync method fires the DoWork event.
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10; i++)
{
bgw.ReportProgress((i + 1) * 10);
Thread.Sleep(1000);
}
}
In the preceding code, I am basically just running a loop that will report the progress of the thread. It will also stop the thread temporarily so that we can see the progress bar move.
Now I will set the progress bar’s value to the percentage that I reported. The progress bar was dragged onto the form from the Toolbox.
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
And last, the code that runs when the task has been completed..
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Finished");
}
And it’s as simple as that.