Fearing I already know the answer. I have a class that handles services calls and caching. To avoid multiple calls to the service with the same request, I can of course use a lock around the code block but a lot of these methods have varying arguments which make up the cache key. It seems a shame to wait for a lock code block to execute when it could be for a completely different cache key (or multiple different cache keys).
I know I could do a lock on the cache key string itself but this is a no-no given that that string could potentially pop up anywhere.
So, I can either perform potential unnecessary calls to the service without the lock OR add potentially unnecessary delays within the method by waiting for the lock.
Are those my only 2 options or is there another?
Cheers
You could, potentially, switch your types around to use a thread safe class, such as a ConcurrentDictionary<T,U>
, to handle your caching. Used appropriately, this would prevent the need for locking (of your own), as you could rely on the fine grained locking built into the concurrent collection itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With