I thought about this for a couple of hours, and I'm a little surprised how difficult it is. I am trying to initialize a static reflection data cache for a given object from a base class that will be accessed from multiple threads. I find it difficult to find the correct template for initializing the cache.
My first thought was that I just initialize the static cache to zero, check to see if it is null in the constructor, and then create and set it if it is not. I.e:.
class TestBase
{
private static ConcurrentDictionary<string, PropertyInfo> Cache;
protected TestBase()
{
if(Cache == null)
{
ConcurrentDictionary<string, PropertyInfo> cache =
new ConcurrentDictionary<string, PropertyInfo>();
Cache = cache;
}
}
}
, , , , (-, ) . , , , , , .
, , , AppDomain , - . , StackOverflow , . , , .
, , / , , , , . .
, Interlocked.Exchange ManualResetEventSlim. :
class TestBase
{
private static ConcurrentDictionary<string, PropertyInfo> Cache;
private static volatile int BuildingCache = 0;
private static ManualResetEventSlim CacheBuilt =
new ManualResetEventSlim();
protected TestBase()
{
if(Interlocked.Exchange(ref BuildingCache, 1) == 0)
{
Cache = new ConcurrentDictionary<string, PropertyInfo>();
CacheBuilt.Set();
}
CacheBuilt.Wait();
}
}
, , , - ? , ? , , , ConcurrentDictionary ( ).