Initialization of objects in the background
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;
}
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.
精彩评论