1

I am wondering about a fail-safe way to call Monitor.TryEnter. The documentation shows it as this:

if (Monitor.TryEnter(lockObj)) {
   try {
      // The critical section.
   }
   finally {
      // Ensure that the lock is released.
      Monitor.Exit(lockObj);
   }
}

As this is the 'official' way to call it, i hesitate to do anything else. But i do not feel very comfortable with that code: Suppose we get a ThreadAbortException like this :

if (Monitor.TryEnter(lockObj)) {
   // *** ThreadAbortException happens exactly here
   try {
      [...]
   }
   finally { [...] }
}

Does that not leave me with a lock that is never released?

  • Why not use `lock (lockObj) { ... }` instead? Also, ThreadAbortException is not a problem usually because the process/appdomain is being torn down anyway. – Lasse V. Karlsen Jun 16 '16 at 06:27
  • @Lasse: lock will not allow me to do something else when the lock is already taken. The threadAbortException does not only occur when the process is torn down, there are more ways to kill a thread. – Ferdinand Swaters Jun 16 '16 at 06:31

2 Answers2

4

You are right. Therefore, the recommended way to use Monitor.TryEnter is:

bool lockAcquired;

try
{
    Monitor.TryEnter(lockObj, ref lockAcquired);

    if (lockAcquired)
    {
        DoSomething();
    }
}
finally
{
    if (lockAcquired)
    {
        Monitor.Exit(lockObj);
    }
}
Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
  • Thanks! I assumed that the code for TryEnter(lock) was the advised code, but now I see that that was the preferred code for the not so preferred overload. – Ferdinand Swaters Jun 16 '16 at 06:16
0

It can be. And you can envelop the all Monitor with a try finally block (with the boolean overload).

About your example of a ThreadAbortException, this is special one. If it throw by the CLR after unload app domain, the CLR will take care for you to do what it needs and after it no code will be run in this app domain so you don't need to worry.

And if you throw it manually, in any way you will be in a bad state...

As side note take a look here, about the trust of of coders in the releasing of the lock in case of exception.

Community
  • 1
  • 1
Dudi Keleti
  • 2,946
  • 18
  • 33