10

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?

Ivan
  • 63,011
  • 101
  • 250
  • 382
  • 2
    quick search -> msdn: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx#Y2337 (look for FibonacciForm) – manji Jun 16 '11 at 00:25
  • 3
    It's just a class like any other, you can create an instance in your code then work with it. This question basically has your answer: http://stackoverflow.com/questions/3767827 – Alastair Pitts Jun 16 '11 at 00:26
  • The way it works can forget quite easily (specially which methods works in main thread and which aren't) but easy to refresh in a few mins. – CharithJ Jun 16 '11 at 00:40
  • 2
    @manji, that example is exactly what Ivan said he wants to avoid, dropping the worker onto a form. I realize for many people this is obvious, but for those who have are self taught or even worse, taught poorly by supervisors, using some components directly without dropping them onto a form is a new concept. This question is clear and doesn't deserve all the down votes. – Samuel Neff Jun 16 '11 at 02:06
  • @Samuel Neff: the example I pointed at (FibonacciForm) uses the `BackgoundWorker`exactly as the OP wants (not droppped in the designer). I also don't like downvoting or commenting just to brag. – manji Jun 16 '11 at 08:59
  • @manji, did you read the example you pointed out? All of the BackgroundWorker code is within the generated form initialization code which means it was dropped on the form, exactly what Ivan said he wants to avoid. – Samuel Neff Jun 16 '11 at 11:08

1 Answers1

33

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...
  }
}
Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
CharithJ
  • 46,289
  • 20
  • 116
  • 131