title: Threading: Locking Under the hood of
body: <p>What happens when we use the lock object? I am aware that it the runtime makes use of the monitor.Enter and Exit methods. But what really happens under the hood? 
  Why only reference types to be used for locking? 
  Even though the object used for accomplishing the locking is changed, how come it still provides thread safety?</p>
  
  <p>In the current sample, we are modifying the object which is used for the locking purpose. Ideally, this is not a preferred way of doing it and best practise is to used a dedicated privately scoped variable. </p>
  
  <pre><code>static List&lt;string&gt; stringList = new List&lt;string&gt;();
      static void AddItems(object o)
      {
          for (int i = 0; i &lt; 100; i++)
          {
              lock (stringList)
              {
                  Thread.Sleep(20);
                  stringList.Add(string.Format("Thread-{0},No-{1}", Thread.CurrentThread.ManagedThreadId, i));
              }
          }
          string[] listArray = null;
  
          lock(stringList)
          listArray = stringList.ToArray();
  
          foreach (string s in listArray)
          {
              Console.WriteLine(s);
          }
      }
  </code></pre>