Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to choose System.Threading over BackgroundWorker?

Why would I decide to choose working directly with System.Threading over BackgroundWorker if the last one abstracts for me the treading managemnet?

I can't see cases where I couldn't use BackgroundWorker to replace System.Threading

like image 855
RollRoll Avatar asked Dec 19 '25 09:12

RollRoll


1 Answers

BackgroundWorker has been around since .NET 2.0 and was intended to aid in writing code that will run in a background thread and not bog down the UI thread. It originally appeared with Windows Forms, but also works with WPF or any future UI framework that registers a synchronization context. It allows you to report progress and results back to the UI thread without having to deal with InvokeRequired/BeginInvoke as well supports cancellation.

The Task Parallel Library (TPL) was introduced in .NET 4 and is intended to model asynchronous tasks. These tasks are asynchronous and may or may not be run on another thread. Examples of something that doesn't run on another thread is asynchronous IO and tasks that need to run on the UI (while still being asynchronous). This task metaphor also supports futures (or continuations) so that you can chain tasks together with ContinueWith, sometimes using specific synchronization contexts so that you can do things like run a task on a UI thread (to update the UI, for example).

Tasks also support cancellation and multiple tasks can share a cancellation token so a requested cancellation cancels multiple tasks.

One of the differences is a Task doesn't have an inherent method of reporting progress back to the UI. Of course it's possible, but it's not built into the interfaces. Tasks also support cancellation.

If you only have one thing you want to do in the background and you specifically want to communicate back to a UI like report progress, I would recommend BackgroundWorker. Otherwise I generally recommend using Task<T> (or Task if no result is necessary). Task is inherently used in the C# 5 async/await syntax...

like image 137
Peter Ritchie Avatar answered Dec 21 '25 00:12

Peter Ritchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!