2

I'm using the C# lock() in my application to ensure that I don't have two or more threads executing the same block of code at the same time. The lock() was added after I did get collisions so I know that it's possible and bad things happen.

Now I'm trying to figure out how to get some sort of feedback/counter that I can use to determine just how often the lock is getting hit. I'm assuming I would have to hook into the Monitor class to get this information but thought I would ask if anyone has addressed this before?

Bob
  • 23
  • 2
  • Possible duplicate of [C# How to detect an object is already locked](https://stackoverflow.com/questions/12033725/c-sharp-how-to-detect-an-object-is-already-locked) – Fruchtzwerg Sep 22 '17 at 04:25
  • That's not a true duplicate because the OP was looking to re-create the native locking mechanism. This question is about getting metrics indicating how frequently threads contend for the lock resource. – Eric J. Sep 22 '17 at 04:47

3 Answers3

3

Depending whether you want to know how many times you got the lock or you didn't, you have two options:

  1. You write your own performance counter and call it inside your lock statement or you just use a simple increment to count.
  2. You use Monitor.TryEnter with a timeout and count how many times you didn't get the lock within the specified time.
slfan
  • 8,950
  • 115
  • 65
  • 78
  • #2 and the other question [C# How to detect an object is already locked](https://stackoverflow.com/questions/12033725/c-sharp-how-to-detect-an-object-is-already-locked) seem the be the accepted way to do this. Since I want the lock the TryEnter() will be in a while loop until I am successful, I'll update a counter once if I can't get the lock (no matter how many times I don't get it). Thanks all for the suggestions. – Bob Sep 24 '17 at 06:04
2

You can use performance counters to determine the total number of unsuccessful attempts by the CLR to acquire thread locks (Total # of Contentions) or the rate per second (Contention Rate / Sec).

https://msdn.microsoft.com/en-us/library/zf749bat(v=vs.110).aspx

Note, this is the total number, so if you have multiple thread contention scenarios in your application, this approach won't break them out into separate counts.

You can get more detailed information about concurrency issues using the profiler built into Visual Studio. If you're on VS 2015, you may want to check out the Concurrency Visualizer (it's not yet available for VS 2017).

Eric J.
  • 147,927
  • 63
  • 340
  • 553
2

Obvious, but tells you how much time spent in the lock, which may be more useful than a count:

private long _lockTicks = 0;

.....

var sw = StopWatch.StartNew();
lock(_locker)
{
   sw.Stop();
   _lockTicks += sw.ElapsedTicks;
   //dostuff
}

......


double seconds = (double)_lockTicks / StopWatch.Frequency;
MineR
  • 2,144
  • 12
  • 18