添加到它时检查ConcurrentDictionary的线程安全方法?

时间:2015-04-07 16:39:29

标签: c# .net parallel.foreach concurrentdictionary

在我的程序中,我正在使用Parallel.Foreach循环遍历“Group”对象列表。在这个循环中,我首先检查我的concurrentdictionary是否存在密钥,以及该值是否包含Group属性。然后我根据字典是否具有键和值将对象添加到列表中。代码如下所示:

var roleUsers = new ExtendedBindingList<RoleUser>();
ConcurrentDictionary<int, List<int>> roleMatch = new ConcurrentDictionary<int, List<int>>();

Parallel.ForEach(groupsWithRole, group =>
            {
                foreach (var u in usersInThisGroup[group.GroupID])
                {
                    if (roleMatch.ContainsKey(u.UserID) && roleMatch[u.UserID].Contains(group.RoleID))
                        continue;

                    //
                    //Unimportant logic
                    //

                        lock (writelock)
                        {
                            roleUsers.Add(roleUser);
                            if (!roleMatch.ContainsKey(u.UserID))
                                roleMatch.TryAdd(u.UserID, new List<int>());
                            roleMatch[u.UserID].Add(group.RoleID);
                        }
                    }
                }
            });

我发现列表roleUsers并不总是具有相同数量的对象,当它非常应该时。这显然是一个线程问题。我的问题是,除了锁定整个事物之外,还有什么方法可以安全地读取和写入concurrentdictionary?

0 个答案:

没有答案