Wednesday, July 31, 2013

Thread vs. BackgroundWorker

Background
There are two classes available in the .NET framework that sometimes have some confusion around them: The Thread and the BackgroundWorker. They're both used to do some heavy lifting for you on a separate thread of execution (so you can keep on keepin' on), so why do we have two different things to accomplish the same end result?

Enter the Thread Class
The Thread class is available in the System.Threading namespace. Surprising, right? It's the basic unit for spawning off work to be done. Threads let you provide them with a name, which could be one advantage to using them. A thread can either operate as "background" which means it will be killed when the application exists, or not as background, which will actually keep the application alive until the thread is killed off.

An instance of the Thread class is relatively lightweight. It's quick to set up for developers and all you need to do is provide it a method to run. You can put a loop in your thread body to keep it alive and do all sorts of fun stuff. Threads are great for setting up queuing, dequeing, scheduling, monitoring, receiving, and listening logic. Well, there are really countless uses for them, but those are some of the big ones I find I do a lot of.

Enter the Background Worker
The BackgroundWorker class is available in the System.ComponentModel namespace. This is slightly different from the Thread class already, and for what it's worth, I generally only have this namespace around if I'm dealing with a UI. That is, if I'm in the equivalent to a data layer or application layer, I usually don't have these guys around (usually, but not necessarily always). So is that it then? Just the namespace is different?

The BackgroundWorker class is essentially built on top of the Thread class. The Thread part of the BackgroundWorker is sort of hidden from you. You get to work with two very important parts of the BackgroundWorker though, the DoWork and RunWorkerCompleted events (There's a progress one too, but because I actually don't use this much I'll omit it for you to take on as homework). So... What are these events all about?

Read more: Codeproject
QR: Inline image 1