I have read the following articles on StackOverflow: ConcurrentBag - Add Multiple Items? and Concurrent Dictionary Correct Usage but the answers are still somehow not obvious to me.
I have this scenario: I have Leaderboard
table in the database and I update it periodically. To optimze the server, I cache the result, so I use ConcurrentDictionary (because there are different types of leaderboards, such as All-time, 3-days, 7-days, etc...).
Here are my code at the updating leaderboard:
var leaderboards = business.UpdateLeaderboard(LeaderboardUpdater.LeaderboardDaySpans, LeaderboardUpdater.LeaderboardCount);
this.LastUpdateTime = now;
// The LeaderboardCache is ConcurrentDictionary<int, LeaderboardResponseViewModel>
this.LeaderboardCache.Clear();
foreach (var leaderboard in leaderboards)
{
this.LeaderboardCache.TryAdd(leaderboard.DaySpan, new LeaderboardResponseViewModel(leaderboard));
}
Assume the user may request Leaderboard information at any time. So I have some questions:
- Should I use
Concat
instead offoreach
to ensure all items are added at the same time? - Even if I use
Concat
, how can I ensure that the user won't request at the middle of theClear
andConcat
method? - Should I apply an additional lock? If so, how can I ensure concurrent read, since multiple read at the same time is okay?