I want to create a cache in my web application, which will allow the top layer (MVC) to persist some values, retrieved from underlying layers (services & DB), in order to avoid unnecessary requests to it. The data, that I want to store in cache, is needed on every page of the web site, so this cache is aimed to dramatically reduce the amount of requests. The idea is that a lot of threads will read the data from collection while one thread will clear it and retrieve new data after cache expiration. This means the collection will be used for frequent reading and rare writing operations.
The problem for me is to choose the appropriate class for these purposes. I have read about the set of concurrent classes from System.Collections.Concurrent
, introduced in .NET 4. I definitely don't need to use ConcurrentQueue
or ConcurrentStack
, but I have to choose between BlockingCollection
, ConcurrentBag
and ConcurrentDictionary
.
ConcurrentBag
seems to be the best solution in this case. However, I read in this article that concurrent dictionary
... is entirely lock-free for read operations. In this way, it’s optimized for scenarios where reading from the dictionary is the most frequent operation.
So maybe the best solution is to use ConcurrentDictionary<int, MyTypeOfObj>
instead? Or maybe I don't need concurrent type at all and simple List
will do the job? Probably, it would do if I can somehow lock operations with it for the time of cache update. But using simple lock
is undesirable.
Any advices and explanations are appreciated.
Update
The cache is used to store the map points of the outlets. The set of outlets is quite stable, but there should be a UI to add them, so insert operations are really rare. It might be even easier to retrieve whole collection from the underlying layer after timeout then perform insert operations. Search is not required as well, reading means simple enumeration.