I tried to use Monitor.TryEnter() to avoid multiple access to critical code areas. Unfortunately, I seem to do something wrong because the locking has no effect. I created a console code snippet to show my problem:
class Program
{
static object _lockObject = new object();
static void Main(string[] args)
{
if (Monitor.TryEnter(_lockObject, 0))
{
try
{
if (Monitor.TryEnter(_lockObject, 0))
{
// I should not be allowed to get here.
Console.WriteLine("Seems it didn't work.");
}
}
finally
{
Monitor.Exit(_lockObject);
}
}
Console.ReadLine();
}
}
I would expect that after locking the object, I could not access it once more, but the lock is obviously ignored. With my GUI, I have the same problem (clicking twice on a button before the operation is finished is not prevented by the Monitor).
What am I doing wrong?