I can remember that many years ago (in 2005) I was using BackgroundWorker in my code without using a visual component for it, but I can't remember how (unfortunately I am very forgetful and forget everything very soon after I stop using it). Perhaps I was extending BackgroundWorker class. Can you link to a good example of using BackgroundWorker this way?
BackgroundWorker enables a simple multithreaded architecture for VB.NET programs. This is more reliable, and easier, than trying to handle threads directly. In the Toolbox pane, please double-click on the BackgroundWorker icon. This will add a BackgroundWorker1 instance to the tray at the bottom of the screen.
BackgroundWorker makes the implementation of threads 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.
A BackgroundWorker component executes code in a separate dedicated secondary thread. In this article, I will demonstrate how to use the BackgroundWorker component to execute a time-consuming process while the main thread is still available to the user interface.
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running.
This article explains everything you need clearly.
Here are the minimum steps in using BackgroundWorker:
- Instantiate BackgroundWorker and handle the DoWork event.
- Call RunWorkerAsync, optionally with an object argument.
This then sets it in motion. Any argument passed to RunWorkerAsync will be forwarded to DoWork’s event handler, via the event argument’s Argument property. Here’s an example:
class Program
{
static BackgroundWorker _bw = new BackgroundWorker();
static void Main()
{
_bw.DoWork += bw_DoWork;
_bw.RunWorkerAsync ("Message to worker");
Console.ReadLine();
}
static void bw_DoWork (object sender, DoWorkEventArgs e)
{
// This is called on the worker thread
Console.WriteLine (e.Argument); // writes "Message to worker"
// Perform time-consuming task...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With