I'm not a thread expert, but in order for the number of times other threads tried to work on an object, you probably have to implement a more primitive version of the lock mechanism than Lock . I gave him a snapshot with a tightly looped Monitor.TryEnter and comments are welcome.
Of course, the implementation of something like this in itself can easily lead to an increase in blocking time and more blocks in order to get the scores you need, and on the basis of the fact that this implementation is certainly not identical to how the lock works inside . Anyway, I wasted time, so I'm going to post it.
class Program { static object lockObj = new object(); static void Main(string[] args) { System.Threading.Thread t = new System.Threading.Thread(proc); System.Threading.Thread t2 = new System.Threading.Thread(proc); t.Start(); t2.Start(); t.Join(); t2.Join(); Console.WriteLine("Total locked up time = " + (LockWithCount.TotalWaitTicks / 10000) + "ms"); Console.WriteLine("Total blocks = " + LockWithCount.TotalBlocks); Console.ReadLine(); } static void proc() { for (int x = 0; x < 100; x++) { using (new LockWithCount(lockObj)) { System.Threading.Thread.Sleep(10); } } } }
The above shows how to use LockWithCount by replacing an existing Lock() {} with using(new LockWithCount(x)) {}
class LockWithCount : IDisposable { static System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); object lockObj; public static long TotalWaitTicks = 0; public static long TotalBlocks = 0; static LockWithCount() { watch.Start(); } public LockWithCount(object obj) { lockObj = obj; long startTicks = watch.ElapsedTicks; if (!System.Threading.Monitor.TryEnter(lockObj)) { System.Threading.Interlocked.Increment(ref TotalBlocks); System.Threading.Monitor.Enter(lockObj); System.Threading.Interlocked.Add(ref TotalWaitTicks, watch.ElapsedTicks - startTicks); } } public void Dispose() { System.Threading.Monitor.Exit(lockObj); } }
source share