I’m reading a book about parallel programming an it says that it’s not thread save to add elements to list without using lock as result will be unpredictable. For example if we have to add 800 000 elements to list, final result will have less then 800 000 elements.
Now I am wondering if it is thread save to read elements from the list. For example lets say that I have a list BlackListedNumbers
List<int> BlackListedNumbers = new List<int> {10, 50 ....... n};
//lets say there is 500 000 elements in the list
and another list Numbers containing 10 000 000 numbers, obviously I’ll use parallel.Foreach to complete this task and what I want is Final list containing all numbers from Numbers that are not in BlackListedNumbers list
List<int> finalList = new List<int>();
Parallel.ForEach(Numbrs,
num =>
{
if (!blackListedNumbrs.Contains(num))
{
lock (finalList)
{
finalList.Add(num);
}
}
});
I know that this is not the most efficient way to get this done but I’m just trying to illustrate the problem.
So my question is: Is it thread save to read result from List blackListedNumbrs and will I get 100% accurate results?
From MSDN:
So if you never modify the list, you should be fine.
Note that using a
HashSet<int>would be rather more efficient – andHashSet<T>also supports multiple readers1. You can also use Parallel LINQ to make your query sweeter and almost certainly more efficient:Much nicer, and no locking required 🙂
1 As noted in comments, I don’t have any documentation to back this up. But reading from a set doesn’t need to modify any shared state, so it at least makes sense…