Is background worker a thread? (C#)
Is background worker 开发者_StackOverflow中文版a thread? When should I use it?
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.
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
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.
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.
精彩评论