Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker and Threads

What are the pros and cons in using the either for achieving a given task.

The million dollar question is which one to use and when?

Many Thanks.

like image 745
Anand Shah Avatar asked Apr 14 '09 14:04

Anand Shah


People also ask

Is BackgroundWorker threaded?

BackgroundWorker, is a component in . NET Framework, that allows executing code as a separate thread and then report progress and completion back to the UI.

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.

Is BackgroundWorker obsolete?

BackgroundWorker is explicitly labeled as obsolete in . NET 4.5: in the book By Joseph Albahari, Ben Albahari "C# 5.0 in a Nutshell: The Definitive Reference"

What is use of BackgroundWorker in C#?

BackgroundWorker is the class in System. ComponentModel which is used when you need to do some task on the back-end or in different thread while keeping the UI available to users (not freezing the user) and at the same time, reporting the progress of the same.


1 Answers

If by "Threads" you mean explicitly using the System.Threading.Thread class to create, configure and kick off your own threads, then the answer is that doing this is more work on your part, involves more cpu cycles than just pulling a thread from the thread pool, (wjhich is what the other techniques do), but it gives you more flexibility, as it allows you to specify thread priority, and several other characteristics that using Thread Pool threads does not afford you.

The "Thread Pool" approach is more appropriate when the number of threads required is not known at design time. The pool initially contains a small number of threads, “ready” for you to call upon them. It can dynamically create new threads on demand, and it manages creation, coordination, and deletion of unused threads for you. There are three mechanisms you can use to access and use threads from the pool.

  1. Using Delegate.BeginInvoke() (the most common technique)
  2. Using timers (several variations)
  3. System.Threading.ThreadPool provides several other features (BackGroundWorker class, QueueUserWorkItem(), etc.).
like image 161
Charles Bretana Avatar answered Oct 10 '22 03:10

Charles Bretana