Thursday, June 5, 2008

C# Progress/Busy Window

I've been playing around with using a C# progress window. For testing I setup a project that takes three different approaches. I used a simple XML serialisation project as a base, and added in some sleep commands to make the serialisation command take about 10 seconds. The first approach uses a simple form (which doesn't work very nicely), then second uses a simple form with a background thread, and the third uses a form with a cancel button and a progress bar with a background thread.

The upshot is, that you need to use a BackgroundWorkerProcess. You need to encapsulate the stuff you want to do in the background into a single function; you need to identify where your bottleneck is. You send your job, that is going to take some time, to a background worker thread, and that keeps the UI responsive; it makes sure that your "I'm busy right now" window stays refreshed. There are two key things you need to do to get this to work:

1. Make sure that your work to be done in the background, doesn't try to touch the user interface. If you need to show progress then you can use the backgroundWorker.Progress method. Your background process should do its work and then return the data (via e.Result) which can then be populated onto the form if required.

2. Make sure you lock down the UI when you launch the work. The UI will remain active and you don't want the user to open a new screen or start the same update again etc, so you need to disable these buttons as required.

One thing you might want to do if you are waiting on a single network request (and therefore can't really determine % complete for a progress bar) is to display an animation - like some whirring cogs or some papers shuffling.

No comments: