Wednesday, July 8, 2009

Hide! Hide in the back!

Article scope

  • Provide a swift review of available async design patterns.
  • Introduce a background threads manager using the nice BackgroundWorker class.

Introduction to secretly doing bad things without the UI knowing them

Basically, as MSDN informs us, there are two ways of implementing asynchronous operations:

  1. Using the IAsyncResult objects.
  2. Using events.

Both of them are design patterns easy to implement. But not long ago, a nice class has been provided to us to please our never ending needs for a less work – more results component. It’s called BackgroundWorker and it’s cool! It allows you to run operations on separate threads, far from the needy UI.

BackgroundWorker in action

Here are the steps you need to take to use BackgroundWorker:

  1. Create a BackgroundWorker instance.
  2. Set its properties WorkerReportProgress and WorkerSupportsCancellation to true or false.
  3. Add event handlers to its DoWork, ProgressChanged, and RunWorkerCompleted events.
  4. Handle those events.
  5. Call RunWorkerAsync with or without a parameter.

Limitations, as provided by MSDN:

  • Do not manipulate any UI object in the DoWork event handler. Do any UI manipulation in the ProgressChanged and RunWorkerCompleted events.
  • Events are not marshaled across AppDomain boundaries.

So why would I need a manager?

Well, it mainly depends on your application’s necessities. If you want to load data from a server and present it to the user, then an implementation of the BackgroundWorker would be more than welcome. I mean, why over generalize stuff? It does no good for developers. But, what if every action a user performs demands the use of asynchronous calls? I don’t want multiple instances of BackgroundWorker in my code or other semi-professional implementations of it. So, let’s couple the action I need to perform and the methods that help me succeed in loading, processing, and getting the data to the UI (the asynchronous workflow).

The BackgroundThreadsManager

It’s a generic class that is supposed to get an enumeration of actions. For example:


See full detail: http://www.codeproject.com/KB/threads/Hide__Hide_in_the_back_.aspx

No comments: