如何获取等待进入锁的线程数量?
How to get the amount of threads waiting to enter a lock?
是否有可能获得一个值,该值指示有多少线程正在等待获取某个对象上的锁?
不,但是您可以将锁封装在 class 中,它可以:
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。
是否有可能获得一个值,该值指示有多少线程正在等待获取某个对象上的锁?
不,但是您可以将锁封装在 class 中,它可以:
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。