.NET List Thread-Safe Implementation Suggestion needed

Posted by Bamboo on Stack Overflow See other posts from Stack Overflow or by Bamboo
Published on 2011-09-19T17:34:07Z Indexed on 2012/06/02 4:40 UTC
Read the original article Hit count: 139

Filed under:
|
|

.Net List class isn't thread safe. I hope to achieve the minimal lock needed and yet still fulfilling the requirement such that as for reading, phantom record is allowed, and for writing, they must be thread-safe so there won't be any lost updates.

So I have something like

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")
          }

All I did was locking write accesses, and allow read accesses to go through without any locking. Is my thread safety idea valid?

I understand there is List size expansion. Will it be ok? My guess is that when a List is expanding, it may uses a temp. list. This is ok becasue the temp list size will always have a boundary, and .Net class is well implemented, ie. there shouldn't be any indexOutOfBound or circular reference problems when reading was caught in updates.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about list