List <>线程的c#用法是否安全?

use*_*056 0 c#

我有C#.Net 4代码,它添加到Parallel.For中的List <>.如果这是线程安全的话,我找不到明确的答案.如果不安全有哪些替代方案?

    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;
    }
Run Code Online (Sandbox Code Playgroud)

Tim*_* S. 10

不,它不是线程安全的.您可能正在寻找ConcurrentBag<T>,一个线程安全的无序集合.MSDN的Thread-Safe Collections文档中提供了更多信息和其他线程安全集合.例如

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;
}
Run Code Online (Sandbox Code Playgroud)