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?
class Program
{
static void Main(string[] args)
{
Test t = new Test();
for (int x = 0; x < 100; x++)
{
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread(t.ProtectedMethod);
threads[i].Start();
}
for (int i = 0; i < 10; i++)
threads[i].Join();
Console.WriteLine("Done with {0}", t.i);
}
}
}
class Test
{
public int i = 0;
public void ProtectedMethod()
{
lock (this)
{
i++;
}
}
}