美文网首页
Lazy Initialization

Lazy Initialization

作者: pillowBalcony | 来源:发表于2017-04-12 13:47 被阅读0次

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

Or you can do like this:


Snippet from Queue<T>:

object SyncRoot
{
  get
  {
    if (_syncRoot == null)
      Interlocked.CompareExchange<object>(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<T> 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

      本文链接:https://www.haomeiwen.com/subject/rslmattx.html