title: Double checked locking in C#
body: <p>The idea is to get a value ("data") from </p>
  
  <ul>
  <li>a variable</li>
  <li>if doesn't exist, then from a file</li>
  <li>if doesn't exist, then from a server</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>public static string LoadData(int id)
  {
      if (_isDataLoaded[id - 1])
      {
        return _data[id - 1];
      }
  
      if (File.Exists(_fileName))
      {
          bool dataExists;
          string cachedData;
          if (GetCachedConstant(id, out cachedData)) //read from a file
          {
              lock (_locker)
              {
                  _isDataLoaded[id - 1] = true;
                  _data[id - 1] = cachedData;
              }
  
              return _data[id - 1];
          }
      }
  
      string remoteData = GetFromServer(id);
      lock (_locker)
      {
          CacheToFile(id, remoteData); //write to a file
          _data[id - 1] = remoteData;
          _isDataLoaded[id - 1] = true;
      }
  
      return _data[id - 1];
  }
  </code></pre>
  
  <p>This code is used by many threads. Although it seems to be thread safe, actually it isn't. I tested it, thus, that gives me that idea and makes me sure. There should be double check of existing <code>_data</code> before writing. For example, it should be like double check used in pattern Singleton usually. </p>
  
  <p>Someone please let me understand how do I implement it here?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <pre><code>string[] _data;
  bool[] _isDataLoaded.
  </code></pre>
  
  <p><strong>EDIT2</strong>:</p>
  
  <p>The code above might be used with .NET &lt; 4.0, so it's not allowed to use Lasy there. The only question I have for now, is should I use volatile in case I would use double-checked locking?</p>
  
  <pre><code>volatile string[] _data;
  volatile bool[] _isDataLoaded.
  </code></pre>