How expensive is the lock statement?

Kees C. Bakker picture Kees C. Bakker · Jan 12, 2011 · Viewed 40.3k times · Source

I've been experimenting with multi threading and parallel processing and I needed a counter to do some basic counting and statistic analysis of the speed of the processing. To avoid problems with concurrent use of my class I've used a lock statement on a private variable in my class:

private object mutex = new object();

public void Count(int amount)
{
 lock(mutex)
 {
  done += amount;
 }
}

But I was wondering... how expensive is locking a variable? What are the negative effects on performance?

Answer

Jake Pearson picture Jake Pearson · Jan 12, 2011

Here is an article that goes into the cost. Short answer is 50ns.