title: Lazy loading and the use of Thread.MemoryBarrier
body: <p>When designing a class that has a reference to another object it might be beneficial to only create the referenced object the first time it is used, e.g. use lazy loading.</p>
  
  <p>I often use this pattern to create a lazy loaded property:</p>
  
  <pre><code>Encoding utf8NoBomEncoding;
  
  Encoding Utf8NoBomEncoding {
    get {
      return this.utf8NoBomEncoding ?? 
        (this.utf8NoBomEncoding = new UTF8Encoding(false));
    }
  }
  </code></pre>
  
  <p>Then I came across this code when browsing the source code for the BCL:</p>
  
  <pre><code>Encoding Utf8NoBomEncoding {
    get {
      if (this.utf8NoBomEncoding == null) {
        var encoding = new UTF8Encoding(false);
        Thread.MemoryBarrier();
        this.utf8NoBomEncoding = encoding;
      }
      return this.utf8NoBomEncoding;
    }
  }
  </code></pre>
  
  <p>As far as I can tell none of these are thread safe. E.g. multiple <code>Encoding</code> objects may be created. I completely get that and know that it isn't a problem if an extra <code>Encoding</code> object is created. It is immutable and will soon be garbage collection.</p>
  
  <p><strong>However, I'm really curious to understand why <code>Thread.MemoryBarrier</code> is necessary and how the second implementation is different from the first in multi-threading scenarios.</strong></p>
  
  <p>Obviously, if thread safety is a concern the best implementation is probably to use <code>Lazy&lt;T&gt;</code>:</p>
  
  <pre><code>Lazy&lt;Encoding&gt; lazyUtf8NoBomEncoding = 
    new Lazy&lt;Encoding&gt;(() =&gt; new UTF8Encoding(false));
  
  Encoding Utf8NoBomEncoding {
    get {
      return this.lazyUtf8NoBomEncoding.Value;
    }
  }
  </code></pre>