title: C# manual lock/unlock
body: <p>I have a function in C# that can be called multiple times from multiple threads and I want it to be done only once so I thought about this:</p>
  
  <pre><code>class MyClass
  {
      bool done = false;
      public void DoSomething()
      {
          lock(this)
              if(!done)
              {
                  done = true;
                  _DoSomething();
              }
      }
  }
  </code></pre>
  
  <p>The problem is <code>_DoSomething</code> takes a long time and I don't want many threads to wait on it when they can just see that <code>done</code> is true.<br>
  Something like this can be a workaround:</p>
  
  <pre><code>class MyClass
  {
      bool done = false;
      public void DoSomething()
      {
          bool doIt = false;
          lock(this)
              if(!done)
                  doIt = done = true;
          if(doIt)
               _DoSomething();
      }
  }
  </code></pre>
  
  <p>But just doing the locking and unlocking manually will be much better.<br>
  How can I manually lock and unlock just like the <code>lock(object)</code> does? I need it to use same interface as <code>lock</code> so that this manual way and <code>lock</code> will block each other (for more complex cases).</p>