BackgroundWorker

Tue, May 27, 2008, 08:36 PM under dotNET | Silverlight
A cool class that was introduced in .NET Framework v2.0 is the BackgroundWorker. If you do any kind of UI development I encourage you to learn about this class (e.g. by following the links below), which makes it easy to execute long running operations on a separate thread, supporting cancellation, progress reporting and marshalling results back to the UI thread.


Back in 2004 I described what the class looks like (inc. links to MSDN) when I implemented it for the .NET Compact Framework v1.0/v2.0 (and for .NET Framework v1.1): BackgroundWorker. I also provided sample code to demonstrate the usage.

An added incentive to learn about it is that Silverlight 2 includes a fully interface-compatible version of BackgroundWorker. A good way to learn about it is by porting to Silverlight the desktop PI sample from my previous blog post and follow what the code does... have fun!
Tuesday, 27 May 2008 21:23:00 (Pacific Daylight Time, UTC-07:00)
Nice! The BackgroundWorker is one of my favorite classes, and I'm glad to see that it's made it into Silverlight.

I've been doing some interesting stuff with a typesafe wrapper for the BackgroundWorker that allows it to be used with anonymous types and anonymous delegates.

If anyone's interested, I posted a short demo over here.


http://thevalerios.net/matt/2008/05/a-type-safe-backgroundworker-wrapper/

It really cleans up the code into a nice, easy-to-read format by having an input argument, the code that gets executed on the background thread, and the code that gets executed on the UI thread when it's finished. It doesn't support progress or cancellation, but you could add that if you really needed it :)
Wednesday, 28 May 2008 03:07:00 (Pacific Daylight Time, UTC-07:00)
problem I've always had with the BackgroundWorker is that if an exception occurs in the worker event and you don't capture that exception then you get no feedback at all on the exception, even if you have a global application exception handler.

Is there some easy way to catch exceptions that are thrown in a background worker, or do I just need to wrap the whole method in a try/catch?
Wednesday, 28 May 2008 03:55:00 (Pacific Daylight Time, UTC-07:00)
There's also a very clever alternative in the System.Threading.Timer class which can be used for simple operations where you want to go and run a timed operation on a separate thread.
Anonymous
Wednesday, 11 June 2008 04:02:00 (Pacific Daylight Time, UTC-07:00)
Here is some thoughts on how to enhance the BackgroundWorker capabilities for certain scenario not handled by default:
http://codebetter.com/blogs/patricksmacchia/archive/2008/06/10/backgroundworker-closure-and-overridable-task.aspx
Comments are closed.