title: Question on using Monitor.TryEnter and locking object
body: <p>Consider the following function that implements non-blocking access to only the one thread.</p>
  
  <pre><code>public bool TryCancelGroup()
  {
      if (Monitor.TryEnter(_locked))
      {
          if (_locked == false)
          {
              _locked = true;
  
              try
              {
                  // do something
              }
              catch (Exception ex)
              {
                  _locked = false;
              }
              finally
              {
                  Monitor.Exit(_locked);
              }
          }
          return _locked;
      }
      else
      {
          return false;
      }
  }
  </code></pre>
  
  <p>And here is how <code>_locked</code> variable is defined.</p>
  
  <pre><code>bool _locked = false;
  </code></pre>
  
  <p>Now when program reaches <code>Monitor.Exit(_locked);</code> it throws an <code>System.Threading.SynchronizationLockException</code> saying that _locked variable was not synchronized before. </p>
  
  <p>It all was working before when _locked variable was defined as object</p>
  
  <pre><code>object _locked = new object();
  </code></pre>
  
  <p>When I changed it to bool in order to use it as boolean flag I started getting this exception.</p>