c# - Lock ConcurrentDictionary while removing and adding multiple items? -


i have read following articles on stackoverflow: concurrentbag - add multiple items? , concurrent dictionary correct usage answers still somehow not obvious me.

i have scenario: have leaderboard table in database , update periodically. optimze server, cache result, use concurrentdictionary (because there different types of leaderboards, such all-time, 3-days, 7-days, etc...).

here code @ updating leaderboard:

        var leaderboards = business.updateleaderboard(leaderboardupdater.leaderboarddayspans, leaderboardupdater.leaderboardcount);         this.lastupdatetime = now;          // leaderboardcache concurrentdictionary<int, leaderboardresponseviewmodel>         this.leaderboardcache.clear();         foreach (var leaderboard in leaderboards)         {             this.leaderboardcache.tryadd(leaderboard.dayspan, new leaderboardresponseviewmodel(leaderboard));         } 

assume user may request leaderboard information @ time. have questions:

  • should use concat instead of foreach ensure items added @ same time?
  • even if use concat, how can ensure user won't request @ middle of clear , concat method?
  • should apply additional lock? if so, how can ensure concurrent read, since multiple read @ same time okay?

you managing concurrency @ wrong level. apparently, want treat dictionary contents atomically synchronizing (unsuccessfully) @ item level.

use following data structure:

volatile lazy<...> mycache = new lazy<dictionary<...>>(producecachevalues); 

when want refresh cache values create new lazy , overwrite mycache.

alternatively, use lock. low-frequency short-duration operations that's enough.

to clarify, there no way make multiple items or operations in concurrentdictionary atomic.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -