Is this usage of List<T> thread safe?

c#, parallel.for, thread-safety

Solution

No, it's not thread-safe. You might be looking for the `ConcurrentBag<T>` class, a thread-safe unordered collection. Some more info and other thread-safe collections are available at MSDN's Thread-Safe Collections documentation. E.g.

static List<int> Calculate(List<string[]> numbers)
{
       var sums = new ConcurrentBag<int>();


        Parallel.ForEach(numbers,
        (nums) =>
        {
            int sum = 0;
            for (int i = 0; i < nums.Length; i++)
                 sum += Convert.ToInt32( nums[i]);

            sums.Add(sum);
        });

        var sorted = sums.OrderBy(x => x).ToList();
        return sorted;
}

Problem

I have C# .NET 4 code which is adding to a `List<string>` inside a `Parallel.For`. I can't find a definite answer to if this is thread-safe or not. If it is unsafe what are the alternatives? ``` static List<int> Calculate(List<string[]> numbers) { List<int> sums = new List<int>(); Parallel.ForEach(numbers, (nums) => { int sum = 0; for (int i = 0; i < nums.Length; i++) sum += Convert.ToInt32( nums[i]); // is this thread safe or not??? sums.Add(sum); }); sums.Sort(); return sums; } ```

Original source

Related problems