ConcurrentBag并行,不保证顺序,线程安全

public static void ConcurrentBagWithPallel()
{
    ConcurrentBag<int> list = new ConcurrentBag<int>();
    Parallel.For(0, 10000, item =>
    {
        list.Add(item);
    });
    //能够达到10000
    Console.WriteLine("ConcurrentBag's count is {0}", list.Count());
    int n = 0;
    foreach(int i in list)
    {
        if (n > 10)
            break;
        n++;
    //输出结果随机,因为是并行的
        Console.WriteLine("Item[{0}] = {1}",n,i);
    }
    Console.WriteLine("ConcurrentBag's max item is {0}", list.Max());
}

结果

 
线程安全ConcurrentBag-LMLPHP
05-11 18:17