title: Concurrency with reading but locking with mutating
body: <p>I'm looking for a solution that allows multiple threads to read the shared resource (concurrency permitted) but then locks these reading threads once a thread enters a mutating block, to achieve best of both world. </p>
  
  <p>I've looked up this <a href="https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx" rel="nofollow noreferrer">reference</a> but it seems the solution is to lock both reading and writing threads.</p>
  
  <pre><code>class Foo {
  
      List&lt;string&gt; sharedResource;
  
      public void reading() // multiple reading threads allowed, concurrency ok, lock this only if a thread enters the mutating block below.
      {
  
      }
  
      public void mutating() // this should lock any threads entering this block as well as lock the reading threads above
      {
          lock(this)
          {
          }
      }
  }
  </code></pre>
  
  <p>Is there such a solution in C#?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>All threads entering in both <code>GetMultiton</code> and constructor should return the same instance. want them to be thread safe.</p>
  
  <pre><code>class Foo: IFoo {
      public static IFoo GetMultiton(string key, Func&lt;IFoo&gt; fooRef)
      {
          if (instances.TryGetValue(key, out IFoo obj))
          {
              return obj;
          }
          return fooRef();
      }
  
       public Foo(string key) {
            instances.Add(key, this);
       }
  }
  
       protected static readonly IDictionary&lt;string, IFoo&gt; instances = new ConcurrentDictionary&lt;string, IFoo&gt;();
  </code></pre>
  
  <p>Use</p>
  
  <pre><code>  Foo.GetMultiton("key1", () =&gt; new Foo("key1"));
  </code></pre>