Search code examples
c#cachingusing

C# using statement cache


It must be a very dump question but I am wondering if I can use a cached object as part of the using statement e.g

using(Class1 sample = Cache.GetClass<Class1>())

Cache.class is a static class which uses memoryCache to store a copy of Class1, and the GetClass is to get a copy of the stored object from cache if it is already there.

In my real life (almost, but simpilfied) exmaple, I have got this:

using (dataDesignerClass dds = Cache.GetClass<dataDesignerClass>()){
   ...
   Dataset ds = new Dataset();
   dds.dataadapter1.fill(ds); //dds is the data designer which contains all the sqlconnection, sql commands, adapters..etc which can get quite big
   ...
}

..which seems to be ok to me, but I find that SOMETIMES the dataset (ds) is not filled by the dataadapter1, without returning error.

My GetClass static class:

 public static T GetClass<T> () where T: class
        {
            string keyName = "CACHE_" + typeof(T).Name.ToUpper();
            CacheItem cacheItem = null;

            cacheItem = GetCache(keyName); //a function to return the cache item
            if (cacheItem == null)
            {
                T daClass = Activator.CreateInstance(typeof(T)) as T;  //the constructor will call the initilalization routine        
                AddCache(keyName, daClass);
                return daClass;
            }
            return (T)cacheItem.Value;            
        }

Can someone explain why it fails?


Solution

  • Reusing a shared object is sometimes good practice, but you need to make sure it can be reused. In your program, you are storing a data adapter in the cache and trying to reuse it between different threads, that causes strange results sometimes because the data adapter can't be shared. Imaging two threads get a same instance of your adapter and modify it at the same time! IMO the data adapter is quite lite and you can create a new instance for each db read, it's unnecessary to cache and reuse it, that makes things complex.