Background Worker for WaitingBar Control in C#.NET
KetticWaitingBar control is a .NET component that shows a running operation. However, when we execute a long running operation on the same thread, the primary UI thread, as the waiting animation, the KetticWaitingBar will freeze and will not move the indicator. As a result, we cannot update the user interface to the form and cannot perform the waiting animation. To solve this issue, we should add a new UI thread to start the time consuming operation. In the C# tutorial below, we will use the Background Worker to achieve this.
BackgroundWorker for Waiting Bar Animation in C#.NET
The following Windows application uses the BackgroundWorker to create waiting bar animation. The C# code sample below provides the detailed description.
- First, load the Windows Form and initialize the BackgroundWorker instance, and then subscribe to the events, DoWork() and RunWorkerCompleted(). The C# code snippet below shows how to achieve this.
private void Form1_Load(object sender, EventArgs e)
myBackgroundWorker = new BackgroundWorker();
myBackgroundWorker.WorkerReportsProgress = true;
myBackgroundWorker.WorkerSupportsCancellation = true;
myBackgroundWorker.DoWork += new DoWorkEventHandler(myBackgroundWorker1_DoWork);
myBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(myBackgroundWorker1_RunWorkerCompleted);
- Second, when clicking the Start KetticButton, we should use the RunWorkerAsync() method to run the BackgroundWorker and use the StartWaiting() method to start the KetticWaitingBar waiting animation. The C# code snippet below can achieve this.
private void ketticButton1_Click(object sender, EventArgs e)
this.ketticButton1.Enabled = false;
this.ketticButton2.Enabled = true;
begin = DateTime.Now;
this.ketticLabel1.Text = "Calculations in process...";
- Third, we shall execute the time consuming operation in the DoWork event handler to calculate the number with the C# code below
- Forth, after the long running operation has completed, we shall use the StopWaiting() method to terminate the waiting animation of the control and show the result