问题
Is it possible to get a value which indicates how many threads are waiting to acquire a lock on a certain object?
回答1:
No, but you could incapsulate the lock in a class that does:
Interlocked.Increment
before entering the lock on a counter and
Interlocked.Decrement
after attaining the lock
For example:
public sealed class SimpleCountedLock
{
private readonly object obj = new object();
private int counter;
public int Counter
{
get
{
// Guaranteed to return the last value
return Interlocked.CompareExchange(ref counter, 0, 0);
}
}
public void Enter(ref bool lockTaken)
{
int cnt = int.MinValue;
try
{
try
{
}
finally
{
// Finally code can't be interrupted by asyncronous exceptions
cnt = Interlocked.Increment(ref counter);
}
Monitor.Enter(obj, ref lockTaken);
}
finally
{
// There could be an asynchronous exception (Thread.Abort for example)
// between the try and the Interlocked.Increment .
// Here we check if the Increment was done
if (cnt != int.MinValue)
{
Interlocked.Decrement(ref counter);
}
}
}
public void Exit()
{
Monitor.Exit(obj);
}
}
Use:
SimpleCountedLock cl = new SimpleCountedLock();
and then in the various threads:
bool lockTaken = false;
try
{
cl.Enter(ref lockTaken);
// Your code. The lock is taken
}
finally
{
if (lockTaken)
{
cl.Exit();
}
}
The reasoning for the ref lockTaken is here: Monitor.Enter.
来源:https://stackoverflow.com/questions/28784953/how-to-get-the-amount-of-threads-waiting-to-enter-a-lock