I'm implementing a simple cache in C#, and trying to make it accessible from multiple threads. In the basic read case, it's easy:
var cacheA = new Dictionary<int, MyObj>(); // Populated in constructor
public MyObj GetCachedObjA(int key)
{
return cacheA[key];
}
This is, I believe, completely thread-safe. But I'd also like to make the it self-loading. That is, if the cache isn't populated on access, it populates it before satisfying the access request.
Dictionary<int, MyObj> cacheB = null;
public MyObj GetCachedObjB(int key)
{
if (cacheB == null)
{
PopulateCacheB();
}
return cacheB[key];
}
private void PopulateCacheB()
{
cacheB = new Dictionary<int, MyObj>();
foreach (MyObj item in databaseAccessor)
{
cacheB.Add(item.Key, item);
}
}
This isn't thread-safe, since a thread could access GetCachedObjB after cacheB is instantiated but before it's fully populated, if another thread is in the process of populating it. So what's the best way to perform locking on cacheB so that the cache is thread-safe?