【发布时间】:2015-07-07 19:29:41
【问题描述】:
我在 StackOverflow 上阅读了以下文章:ConcurrentBag - Add Multiple Items? 和 Concurrent Dictionary Correct Usage,但答案对我来说仍然不明显。
我有这种情况:我在数据库中有Leaderboard 表,我会定期更新它。为了优化服务器,我缓存了结果,所以我使用了 ConcurrentDictionary(因为有不同类型的排行榜,例如 All-time、3-days、7-days 等...)。
这是我在更新排行榜上的代码:
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));
}
假设用户可以随时请求排行榜信息。所以我有一些问题:
- 我是否应该使用
Concat而不是foreach来确保同时添加所有项目? - 即使我使用
Concat,如何确保用户不会在Clear和Concat方法中间请求? - 我应该应用额外的锁吗?如果是这样,我如何确保并发读取,因为同时多个读取是可以的?
【问题讨论】:
标签: c# .net multithreading concurrency concurrentdictionary