多年来,如果它存在的话,我并没有真正遇到过这个问题,所以我要把它放在那里,以了解是否有人知道任何低级.NET功能,可能在反射中,可以捕获线程已经锁定?某种日志记录可能吗?
private object _lockObject = new object();
void MyFunc()
{
lock(_lockObject) // <== How can I understand how many threads are waiting on this?
{
// Do work
}
}
将某种锁处理程序组合在一起并将其传递给谓词如??
是否可行void DoLock(object lockObject, Action predicate)
{
push(threadid);
lock(lockObject)
{
pop(threadid);
predicate();
}
}
答案 0 :(得分:1)
您可以通过PerformanceCounter
获取一些信息。
为此,您需要知道要监视的进程的名称。
效果计数器类别名称为".NET CLR LocksAndThreads"
,该类别的计数器名称显示在我上面链接的页面的表格中。
监控通常是从与被监控的流程不同的流程执行的,但为简单起见,这里有一个监控自身的示例控制台应用程序:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
var counter1 = new PerformanceCounter(".NET CLR LocksAndThreads", "Contention Rate / sec", "ConsoleApp1");
var counter2 = new PerformanceCounter(".NET CLR LocksAndThreads", "Total # of Contentions", "ConsoleApp1");
Task.Run(() => test());
Task.Run(() => test());
Task.Run(() => test());
Task.Run(() => test());
while (true)
{
Thread.Sleep(100);
Console.WriteLine($"Contention: {counter1.NextValue()}/sec, Total: {counter2.NextValue()}");
}
}
static object locker = new object();
static void test()
{
while (true)
{
lock (locker)
{
Thread.Sleep(50);
}
}
}
}
}