Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# to lock or not to lock

Tags:

c#

locking

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

like image 714
johnnyboy Avatar asked Nov 08 '12 21:11

johnnyboy


1 Answers

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.

like image 132
Reed Copsey Avatar answered Sep 23 '22 13:09

Reed Copsey