需要.NET列表线程安全实施建议

时间:2011-09-19 17:34:08

标签: .net list thread-safety

.Net List类不是线程安全的。我希望实现所需的最小锁定,但仍然满足要求,以便读取,允许幻像记录,并且对于写入,它们必须是线程安全的,因此不会有任何丢失的更新。

所以我有类似

的东西
public static List<string> list = new List<string>();

In Methods that have **List.Add**/**List.Remove** , I always lock to assure thread safety

            lock (lockHelper)
            {
                    list.Add(obj);
                    or list.Remove(obj);
            }

In Methods that requires **List Reading** I don't care about phantom record so I go ahead to read without any locking. In this case. Return a bool by checking whether a string had been added.

          if (list.Count() != 0) {
              return list.Contains("some string")
          }

我所做的只是锁定写访问,并允许读访问通过而无需任何锁定。我的线程安全理念是否有效?

我知道列表大小扩展。会没事吗?我的猜测是,当List正在扩展时,它可能会使用temp。名单。这是好的,因为临时列表大小将始终具有边界,并且.Net类已经很好地实现,即。在更新中捕获读取时,不应存在任何indexOutOfBound或循环引用问题。

3 个答案:

答案 0 :(得分:3)

不,这不安全。你应该防止读取和枚举。

由于您使用的是4.0,请查看新的线程安全集合。

http://msdn.microsoft.com/en-us/library/dd997305.aspx

答案 1 :(得分:1)

如果您使用的是.NET Framework 4;为什么不使用ConcurrentBag<T>

答案 2 :(得分:1)

由于您使用的是.NET 4.0,因此您应该使用它提供的ConcurrentBag<T>作为UnorderedList的线程安全实现。

您可以在此处查看所有线程安全的收藏集

.NET Thread Safe Collections

相关问题