0

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?

Thern
  • 1,017
  • 8
  • 17
  • 3
    Monitors are re-entrant; if the thread already has acquired the lock, it may do so again, but then has to release it twice. [See this question](https://stackoverflow.com/questions/34627144/monitors-and-re-entrancy-clarifies-difference-between-re-entrant-code-and-re-en) for details. – Joe Sewell Sep 11 '22 at 22:08
  • I understand now. I should have used a semaphore. Thanks for the hint. – Thern Sep 11 '22 at 22:28

0 Answers0