in the following code example:
class Program
{
private static int counter = 0;
public static object lockRef = new object();
static void Main(string[] args)
{
var th = new Thread(new ThreadStart(() => {
Thread.Sleep(1000);
while (true)
{
Monitor.Enter(Program.lockRef);
++Program.counter;
Monitor.Exit(Program.lockRef);
}
}));
th.Start();
while (true)
{
Monitor.Enter(Program.lockRef);
if (Program.counter != 100)
{
Console.WriteLine(Program.counter);
}
else
{
break;
}
Monitor.Exit(Program.lockRef);
}
Console.Read();
}
}
Why does the while loop inside Main function does not break even if I use lock with Monitor? If I add Thread.Sleep(1) inside the Thread while everything works as expected and even without Monitor…
Is it just happening too fast that the Monitor class doesn't have enough time to lock?
NOTE: The != operator is intended. I know I can set it to < and solve the problem. What I was trying to achieve is to see it working with Monitor class and not working without it. Unfortunately it doesn't work both ways. Thanks