Caching is a common technique that is being used in many applications to increase performance and efficiency. Usually, reading from a cache occurs more often than writing operation, and the number of cache readers is higher that the number of writers.
In this particular case, there is no sense in using an exclusive lock preventing other threads from reading another cache value. There is a built-in synchronization object that has exactly this behavior, and it is called ReaderWriterLockSlim
.
Note
There are several classes in the .NET Framework inside the System.Threading
namespace, whose names end with Slim
. It is usually more efficient and lightweight to implement the corresponding classes without Slim
at the end of their names. In most cases, you should prefer the Slim
versions over original ones, unless you are 100% sure why you need non-slim objects. This rule works with the ReaderWriterLock
and ReaderWriterLockSlim
classes as well—always prefer...