问题
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.
回答1:
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
回答2:
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.
回答3:
You can use a simple shared counter(integer) that increments before the lock statement. If the value is equal to 5 then have your thread avoid the lock statement. The challenge however is that you will need to lock the counter to ensure the increment operation is atomic.
回答4:
No, lock()
uses the Monitor class and that has no member for finding out the nr of queued threads.
You can specify a time-out.
And frankly, throwing an Exception when a queue fills up sounds like a bad idea.
来源:https://stackoverflow.com/questions/4455024/is-there-any-way-to-determine-the-number-of-threads-waiting-to-lock-in-c