Thread locking
If you use locking to ensure only a single thread can access a given resource, some threads may have to wait for a lock to become available.
To see if this is an issue, use perfmon to check the following counters, all in category .NET CLR LocksAndThreads (to see how to do this, refer to the Pinpointing bottlenecks section, the Thread usage subsection in chapter 2):
Category: .NET CLR LocksAndThreads | |
---|---|
Contention Rate/sec |
The rate at which the runtime tries to get a managed lock, and fails to do so. |
Current Queue Length |
Last recorded number of threads waiting to get a managed lock. |
If you consistently have threads failing to get a managed lock, you are looking at a source of delays. You can consider the following ways to reduce these delays:
Minimize the duration of locks
Use granular locks
Use
System.Threading.Interlocked
Use
ReaderWriterLock
Minimizing the duration of locks
Acquire locks on shared resources just before you access them, and release them immediately after...