是否可以获取一个值,该值指示有多少线程等待获取某个对象的锁定?
答案 0 :(得分:1)
不,但你可以在一个类中填充锁:
Interlocked.Increment
在进入柜台锁定之前
Interlocked.Decrement
获得锁定后
例如:
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);
}
}
使用:
SimpleCountedLock cl = new SimpleCountedLock();
然后在各种线程中:
bool lockTaken = false;
try
{
cl.Enter(ref lockTaken);
// Your code. The lock is taken
}
finally
{
if (lockTaken)
{
cl.Exit();
}
}
ref lockTaken的原因在于:Monitor.Enter。