Hi there.
I need to serialize access to shared resource(ie Cache). I use pattern described later, but sometimes, especially the first two threads, loads data twice. Where is the problem?
public class Entity { }
public class CacheManager
{
public static CacheManager Instance = new CacheManager();
private CacheManager()
{
_thisLock = new Object();
_cache = new Dictionary<int, Entity>();
}
private readonly Object _thisLock;
private readonly IDictionary<int, Entity> _cache;
public Entity GetEntity(int id)
{
Entity entity;
if ( !_cache.TryGetValue(id, out entity) ) {
/* Only one thread, at a time, can go inside lock statement.
* So, if threads [1] and [2] came here at the same time, .NET shoud pass thread [1] inside and [2] waits. */
lock ( _thisLock ) {
if ( !_cache.TryGetValue(id, out entity) ) { /* If we are [2] : check(and loads from cache) if [1] did work for us. */
/* we are [1] so let's load entity from repository and add it to cache */
entity = new Entity(); // simulate repository access
_cache.Add(id, entity);
}
}
}
return entity;
}
}
Why both threads steps inside lock statement? Is it becouse i have quad core proccessor? If i add "Thread.Sleep(1);" before the lock statement, everything works fine. Should i use Mutex class?
Thank you.