BackgroundWorker makes threads easy to implement in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done.
ThreadsSteps
In the image, you see the Visual Studio designer view. The fly-out panel is the Toolbox—it contains links for all kinds of controls. It also contains the BackgroundWorker link, which we can use in the following steps.
First, click on BackgroundWorker. You will need to double-click on BackgroundWorker link in the Toolbox. Look at the gray bar near the bottom of your window. A BackgroundWorker will appear there.
Second:Highlight backgroundWorker1. Click on the backgroundWorker1 item in the gray bar on the bottom. Now, look at the Properties panel.
Third:Look for the lightning bolt.
You will see a lightning bolt icon in the Properties pane.
This is Microsoft's icon for events.
Tip:BackgroundWorker is event-driven, so this is where we will make the necessary events to use it.
Then, double-click on DoWork. Sorry, but we have to begin working. Double-click on DoWork, which will tell Visual Studio to make a new "work" method.
In this method,
you will put the important,
processor-intensive stuff.
The rectangles show the tray at the bottom containing the backgroundWorker1 icon, and the Properties panel on the right. The lightning bolt helps us easily add events to the BackgroundWorker.
Tip:This UI is far better than trying to type the methods in manually. It requires less effort on your part.
DoWork
The DoWork method is like any other event handler. Here we must look at the C# view of your file, where we will see the DoWork method. You should see that the backgroundWorker1_DoWork event is generated when you double-click on DoWork.
For testing, let's add a Thread.Sleep command there. The Thread.Sleep method will pause the execution of the BackgroundWorker, but does not consume the entire CPU. It will show us threading is functioning.
SleepExample that shows DoWork event handler: C# using System; using System.ComponentModel; using System.Windows.Forms; using System.Threading; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1 { InitializeComponent; } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { Thread.Sleep(1000); // One second. } } }