Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you link to a good example of using BackgroundWorker without placing it on a form as a component?

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?

like image 657
Ivan Avatar asked Jun 16 '11 00:06

Ivan


People also ask

What is the use of BackgroundWorker in VB net?

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.

What is use of BackgroundWorker in C#?

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.

What is BackgroundWorker in Winforms?

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.

What is a BackgroundWorker?

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.


1 Answers

This article explains everything you need clearly.

Here are the minimum steps in using BackgroundWorker:

  1. Instantiate BackgroundWorker and handle the DoWork event.
  2. 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...
  }
}
like image 198
CharithJ Avatar answered Oct 06 '22 23:10

CharithJ