Is a background worker thread? (FROM#)

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

+6
c #
source share
4 answers

Yes, it's basically like a thread, but with extra functionality (events to notify you of progress and completion).

You have to use it whenever you need to do something that may take some time (for example, calculating, reading and writing files or databases, web requests, etc.) and you do not want the GUI seemed irrelevant during its occurrence:

The BackgroundWorker class allows you to start an operation in a separate dedicated thread. Long operations, such as loading and database transactions, can cause the user interface (UI) to appear as if it stops responding during operation. If you need a responsive interface and are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

Read How to perform an operation in the background for an introduction.

+13
source share

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. } 

See here for more details.

+4
source share

A background worker is basically a stream with the addition that it will call back when it is completed, and this callback will be in the context of the UI so that you can update the UI after completion.

If you need this callback after completion in the context of the UI thread, use it. Otherwise, you should just use a regular thread.

+1
source share

Here is an example application code that displays a progress indicator when sth loads. using background worker

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

and here's a quick background tutorial

http://www.dotnetperls.com/backgroundworker

I suggest you use it when you have a time-consuming operation (file upload, etc.) and you want the user interface to be active. This is a useful feature if you want to show progress on the interface, for example, show the percentage on the label, or you want to use the progress panel.

i especially use it with progressbar control.

0
source share

All Articles