Executing a task with the background worker.
Double Click on the
BackgroundWorker control from the Toolbox
This is how the BackgroundWorker appears after adding it.
Double click on the added control to get the
BackgroundWorker1_DoWork event and add the code to be executed when the BackgroundWorker is called. Something like this:
Calling the BackgroundWorker to perform the task can be done at any event like
Textbox_TextChanged, etc. as follows:
RunWorkerCompleted event to capture the task finished event of the BackgroundWorker as follows:
This will display a message box saying
Done when the worker finishes the task assigned to it.
Accessing GUI components in BackgroundWorker
You cannot access any GUI components from the BackgroudWorker. For example if you try to do something like this
you will receive a runtime error saying that "Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on."
This is because the BackgroundWorker runs your code on another thread in parallel with the main thread, and the GUI components are not thread-safe. You have to set your code to be run on the main thread using the
Invoke method, giving it a delegate:
Or you can use the ReportProgress method of the BackgroundWorker: