0

I've read quite a lot on SO and other sites about cache and thread synchronization, but I still can't get an answer to my question.

.NET Thread Safety for Static Dictionary Cache

How does lock work exactly?

Why are locks performed on separate objects?

http://msdn.microsoft.com/en-us/magazine/cc188793.aspx

...

I'm trying to implement a cache that exposes resources which are only read from the outside. These resources can be updated but it doesn't happen often, and also won't take much time.

Basically the resources are lists of key values (id and string) and aren't really big (hundred elements not much more).

So, I don't want to put a lock on the read method to avoid synchronization overhead since it won't be necessary most of the time, but I'd like to use it when a resource needs to be updated.

My question is: is there a way to do something like this:

public class AFTypeCache<T> where T : class
{
   private Dictionary<int, T> _types;
   private Func<Dictionary<int, T>> _dataProvider;
   private readonly object _sync = new object();

   public void UpdateData()
   {
       // here something (?) to make sure no more threads are reading the resource
       lock (_sync)
       {
           _types = _dataProvider();
       }
   }

   public IEnumerable<int, T> Get()
   {
       // thought about something like that but I'm pretty sure this won't work...
       if (_updating)
       {
           lock
           {
                return _types;
           }
       }
       else
       {
           // I know not the way to get enumerator but that's not the point
           return _types;
       }
   }
}

Also, is it really useful to try to achieve this or am I going the wrong way and just should use a lock in the Get method?

EDIT:

Ok after some more google search, I would have a more precise question: is it possible to know if a class reference is in use by other threads, and if so, wait for this threads to finish using it?

Community
  • 1
  • 1
ppetrov
  • 3,077
  • 2
  • 15
  • 27

1 Answers1

0

am i missing something or you are trying to create a concurrent dictionary? if so, why not use the framework one? (http://msdn.microsoft.com/en-us/library/dd287191.aspx)

you can solve you'r problem with the concurrent dictionary (or you'r own version of it), use the thread id and the class name as the key and the value is the a boolean that indicates the usage of the class in the thread.

but i can't see any reason for doing this, as well, the concurrent dictionary already exists in the framework.

Nadav Ben-Gal
  • 549
  • 3
  • 13
  • I know there is a concurrent dictionnary in the framework, but I think it locks the data on read, that's what I'm trying to avoid. I only need to lock it on update (which doesn't happen often). – ppetrov Mar 29 '13 at 10:46