Lazy Initialization

You could use Lazy class. By default it will support LazyThreadSafetyMode.ExecutionAndPublication.

Or you can do like this:


Snippet from Queue:

object SyncRoot
{
  get
  {
    if (_syncRoot == null)
      Interlocked.CompareExchange(ref _syncRoot, new object(), null);
    return _syncRoot;
  }
}

As Interlocked is a CPU-Level instruction, I think it would be supported by other languages. And this pattern can be used without Lazy class.

Now when two threads first reach line

if (_syncRoot == null)

The first thread calls Interlocked.CompareExchange will assign _syncRoot with new Object(), the latter will do nothing because now _syncRoot would fail to compare with comparand null.

你可能感兴趣的:(Lazy Initialization)