c# - Accessing and Updating Cached Dictionary -
i have dictionary (concurrent) used map 1 object id another. getting value id based on input key rather expensive, want persist dictionary in server cache.
i have first-blush attempt @ method this, "feels" there better way it:
private string getitem(string cachekey, string itemkey) { string sfaccountid = null; concurrentdictionary<string, string> sfaccountmap = context.cache[cachekey] concurrentdictionary<string, string>; if(sfaccountmap == null) { lock(cachelock) { sfaccountmap = context.cache[cachekey] concurrentdictionary<string, string>; if(sfaccountmap == null) { sfaccountmap = new concurrentdictionary<string, string>(); sfaccountid = expensivemethodreturnsstring(); if(!string.isnullorempty(sfaccountid)) { sfaccountmap.tryadd(itemkey, sfaccountid); } context.cache[cachekey] = sfaccountmap; } } } else { if(sfaccountmap.containskey(itemkey)) { sfaccountmap.trygetvalue(itemkey, out sfaccountid); } else { sfaccountmap.tryadd(itemkey, expensivemethodreturnsstring()); lock(cachelock) { context.cache[cachekey] = sfaccountmap; } } } return sfaccountid; }
it appears code can simplified, while still doing doing now.
private concurrentdictionary<string, string> getcachedaccountmap(string cachekey) { var map = context.cache[cachekey] concurrentdictionary<string, string>; if (map == null) { lock (cachelock) { map = context.cache[cachekey] concurrentdictionary<string, string>; if (map == null) map = context.cache[cachekey] = new concurrentdictionary<string, string>(); } } return map; } private string getitem(string cachekey, string itemkey) { return getcachedaccountmap(cachekey) .getoradd(itemkey, k => expensivemethodreturnsstring()); }
note: given unlikely have concurrent access cache while account map not yet there, , appears not bad in exceptional case if 1 allocation , call expensive method, getcachedaccountmap
method further simplified, not using locks.
private concurrentdictionary<string, string> getcachedaccountmap(string cachekey) { var map = context.cache[cachekey] concurrentdictionary<string, string>; if (map == null) map = context.cache[cachekey] = new concurrentdictionary<string, string>(); return map; }
Comments
Post a Comment