views:

52

answers:

1

I need to initialize few objects, it can take a while so I want to do it in some background thread. I also want to display progressBar showing what is the progress of initialization.
What is the most elegant way to do it?

I was thinking about an interface:

interface ILoadable
{
    int Progress { get; }
    event EventHandler Loaded;
}
+8  A: 

Why not just use a BackgroundWorker directly? It provides events for DoWork, ProgressChanged, and RunWorkerCompleted.

The advantage of this (or a thin wrapper over this) is that you automatically get the threading handled for you, properly, and it's very well tested.

If you want to make a wrapper around this, I'd actually recommend making yourself an abstract class that encapsulates the BackgroundWorker, and lets you provide Action delegates for the run operation.

Reed Copsey
That was quick. BackgroundWorker is exactly what I was looking for. Thanks.
Tomek Tarczynski
+1 It also catches exceptions and marshals them back to the UI thread for you, very useful!
Christian Hayter