Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to determine the number of threads waiting to lock in C#?

I'm using simple locking in C# using the lock statement. Is there any way to determine how many other threads are waiting to get a lock on the object? I basically want to limit the number of threads that are waiting for a lock to 5. My code would throw an exception if a sixth thread needs to get a lock.

like image 555
Ben Mills Avatar asked Dec 15 '10 21:12

Ben Mills


2 Answers

This can be easily accomplished via the Semaphore class. It will do the counting for you. Notice in the code below that I use a semaphore to do a non-blocking check of the number of threads waiting for the resource and then I use a plain old lock to actually serialize access to that resource. An exception is thrown if there are more than 5 threads waiting for the resource.

public class YourResourceExecutor
{
  private Semaphore m_Semaphore = new Semaphore(5, 5);

  public void Execute()
  {
    bool acquired = false;
    try
    {
      acquired = m_Semaphore.WaitOne(0);
      if (!acquired)
      {
        throw new InvalidOperationException();
      }
      lock (m_Semaphore)
      {
        // Use the resource here.
      }
    }
    finally
    {
      if (acquired) m_Semaphore.Release();
    }
  }
}

There is one notable variation of this pattern. You could change the name of the method to TryExecute and have it return a bool instead of throwing an exception. It is completely up to you.

Remember that the object used in the lock expression is not the subject of the lock. It merely serves as an identifier for a synchronized block of code. Any code blocks that acquire locks using the same object will effectively be serialized. It is the code block that is being "locked", not the object used in the lock expression

like image 147
Brian Gideon Avatar answered Sep 29 '22 08:09

Brian Gideon


The lock statement is a shortcut for Monitor.Enter and Monitor.Exit. I do not think, that you have a chance to get the number of waiting objects.

like image 30
Uwe Keim Avatar answered Sep 29 '22 07:09

Uwe Keim