How to initialize a static cache of reflection data in a stream

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>();
      // Populate...
      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>();
      // Populate...
      CacheBuilt.Set();
    }
    CacheBuilt.Wait();
  }
}

, , , - ? , ? , , , ConcurrentDictionary ( ).

+3
2

Lazy<T>, - - , .

, Assembly.GetTypes() (, , ). :

var types = typeof(TestBase).Assembly.GetTypes().Where(type => --some condition--);
+3

(private static ConcurrentDictionary<string, PropertyInfo> Cache = new ConcurrentDictionary<string, PropertyInfo>();) , , . , TryAdd , - .

, , IsCahceValid, , . TryAdd, , true , , .

0

All Articles