Is the snippet below “safe” for performing some initialization once in a multithreaded program?
I’m a bit worried that boxing/unboxing might cause some problem…
private static object initialized = false;
public static void Initialize()
{
lock (initialized)
{
if ((bool)initialized == false)
{
DoInitialization();
initialized = true;
}
}
}
Note that I can’t just do the initialization from Main or some other single threaded context.
You are right – that’s not going to work because you are reassigning the object you are locking on.
You can do this with two seperate members – an object to lock on that is assigned only once, and then a boolean that you can read or assign to (after you have locked).
You may also want to consider if a singleton would be appropriate here.