title: Parallel Extensions: Help Me Understand LazyInit<T>
body: <p><strong>Update for future readers:</strong> When .NET 4 comes out, <code>LazyInit&lt;T&gt;</code> from the CTP will have been renamed to <code>Lazy&lt;T&gt;</code> and will be changed from a struct to a class, so very little of this will apply, except as an illustration of why mutable structs can be problematic if you're not careful.</p>
  
  <p>I've been experimenting with LazyInit in the Parallel Extensions June CTP, and I would expect the following code to print out the same Guid a thousand times, but instead it prints out a thousand different Guids. Clearly I'm missing something obvious here about how LazyInit is supposed to work, and I'd appreciate if someone would kindly point out what it is.</p>
  
  <pre><code>using System;
  using System.Diagnostics;
  using System.Threading;
  
  namespace TestApp
  {
      class Program
      {
          static void Main(string[] args)
          {
              for (int i=0; i &lt; 1000; i++)
              {
                  Console.WriteLine(TestClass.Instance.Id);
              }
  
              Console.Write("Press any key to continue:");
              Console.ReadKey();
          }
  
          private class TestClass
          {
              private static readonly LazyInit&lt;TestClass&gt; _instance = new LazyInit&lt;TestClass&gt;(() =&gt; new TestClass(), LazyInitMode.EnsureSingleExecution);
  
              public static TestClass Instance
              {
                  get { return _instance.Value; }
              }
  
              private TestClass()
              {
                  Debug.WriteLine("TestClass Constructor");
                  Id = Guid.NewGuid();
              }
  
              public Guid Id { get; private set; }
          }
      }
  }
  </code></pre>