.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开发者_JS百科 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.
No that is not safe. You should protect against reads and enumerations.
Since you are using 4.0, check out the new thread safe collections.
http://msdn.microsoft.com/en-us/library/dd997305.aspx
If you are using .NET Framework 4; Why not use ConcurrentBag<T>
?
Since you are using .NET 4.0 you should just use the ConcurrentBag<T>
as it provides as threadsafe implementation of an UnorderedList.
You can see all the Thread-Safe Collections here
.NET Thread Safe Collections
精彩评论