Performing a one-time initialization in multithreaded programs in C #

Is the snippet below “safe” to perform some initialization once in a multi-threaded program?

I am a little worried that boxing / unpacking may cause some problems ...

private static object initialized = false;

public static void Initialize()
{
  lock (initialized)
  {
    if ((bool)initialized == false)
    {
      DoInitialization();
      initialized = true;
    }
  }
}

Note that I cannot just initialize from Main or some other single-threaded context.

+3
source share
3 answers

You are right - this will not work because you are reassigning the object that you are locking.

- , , , ( , ).

singleton.

+4

.

    private static volatile bool initialized = false;
    private static object syncObject = new object();
    public static void Initialize() {
        if (!initialized) {
            lock (syncObject) {
                if (!initialized) {
                    DoInitialization();
                    initialized = true;
                }
            }
        }
    }
+3

:

  • , .
  • , , , . Con: , , .
  • , Lazy, .

3 .

+1

Source: https://habr.com/ru/post/1760009/


All Articles