I have a Winform application that I am trying to implement caching in order to speed up the process of reading data everytime one of my class methods get called. I am thinking of using a Singleton-like approach. I am thinking of something like this:
public class MyCache {
private MyDataClass _cacheData;
private static MyCache _cache;
public static MyCache CreateCache()
{
return _cache ?? new MyCache();
}
public void CacheData(MyDataClass data)
{
_cache = data;
}
public MyDataClass GetCache()
{
return _cache;
}
}
Can someone tell me if this approach is good or if there is a better approach I should use?
For your situation, I would suggest form-level caching, i.e. shared/static lists with corresponding properties. By lists I mean any type of object, but most likely it will be a dictionary – to have a
(key,value)pair. Inside each property, ifNothing, populate from database, then read from_variable, so it will only load once. Something like this:If you plan to have more objects in your cache, you might look into creating a
Dictionaryof<YourObjectTypesEnum, Dictionary<String, String>>instead, whereYourObjectTypesEnumcan beVendor,Manufacturing,Locationetc. So you get strict typing in your code, rather than accessing byString. Then you would testContainsKeyinstead of null check and.Addto dictionary if missing.If you later decide to use this cache on other forms, you can easily move it to a separate class, because all methods and properties are static anyway.