title: confused about dangers of lock(this)
body: <p>I wanted to understand dangers of lock(this) with some code example. With the code, if everything works well I expect to see 1000 at the end of program.
  And that's what I get every time I run it even though I am using lock(this). Why lock(this) works well here?</p>
  
  <pre><code>class Program
      {
          static void Main(string[] args)
          {
              Test t = new Test();
              for (int x = 0; x &lt; 100; x++)
              {
                  Thread[] threads = new Thread[10];
                  for (int i = 0; i &lt; 10; i++)
                  {
                      threads[i] = new Thread(t.ProtectedMethod);
                      threads[i].Start();
                  }
  
                  for (int i = 0; i &lt; 10; i++)
                      threads[i].Join();
  
                  Console.WriteLine("Done with {0}", t.i);
              }
  
          }
      }
  
      class Test
      {
          public int i = 0;
  
          public void ProtectedMethod()
          {
              lock (this)
              {
                  i++;
              }
          }
      }
  </code></pre>