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
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?