6

Is background worker a thread? When should I use it?

1
  • I misread just now? I saw you are asking "How should I use it" but now becomes "When should I use it"?
    – Cheng Chen
    Aug 20, 2010 at 2:44

4 Answers 4

13

Yes, it is basically like a thread, but with extra functionality (events to notify you of progress and when it finishes).

You should use it whenever you need to execute something that might take a while (e.g. a calculation, file or database reading/writing, web requests, etc.) and you don’t want the GUI to appear unresponsive while it is happening:

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. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

Read How to: Run an Operation in the Background for an introduction.

0
4

A simple example:

static void Main(string[] args)
{
   BackgroundWorker worker = new BackgroundWorker();
   //DoWork is a delegate, where you can add tasks
   worker.DoWork += (sender, e) =>
      { 
            //blabla
      };
   worker.DoWork += (sender, e) =>
      {
            //blabla
      };
   worker.RunWorkerCompleted += (sender, e) =>
      {
           var IfYouWantTheResult = e.Result;
           //maybe notify others here
      };
   worker.RunWorkerAsync();
   //you can cancel the worker/report its progress by its methods.
}

For more details, check here

1

The background worker is basically a thread with the addition that it will call back when it completes, and that call back will be in the context of the U.I. thread so that you can update the U.I. upon completion.

If you need that callback upon completion in the context of the U.I. thread - use it. Otherwise you should just use a regular thread.

0

here is a sample code of an application which displays a progressbar while downloading sth. using background worker

http://devtoolshed.com/content/c-download-file-progress-bar

and here's a quick tutorial about background worker

http://www.dotnetperls.com/backgroundworker

i suggest you use it when you have a time consuming operation (downloading a file etc.) and you want the UI to be active. it's a useful feature if you want to show the progress on the interface like showing percentage on a label, or you want to use a progressbar.

i especially use it with the progressbar control.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.