张德长

导航

ConcurrentBag线程安全,List线程不安全,示例

   class Program
    {
        static void Main(string[] args)
        {
            ListTest();
            ConcurrentBagTest();
        }


        public static  void ConcurrentBagTest()
        {
            ConcurrentBag<int> bag = new ConcurrentBag<int>();
            List<Task> taskList = new List<Task>();
            for (int i = 0; i < 100; i++)
            {
                int numberToAdd = i;
                taskList.Add(Task.Run(() => bag.Add(numberToAdd)));

            }
            Task.WaitAll(taskList.ToArray());

            List<Task> consumeTaskList = new List<Task>();
            int count = 0;
            while (!bag.IsEmpty)
            {
                consumeTaskList.Add(Task.Run(() =>
                {
                    int temp;
                    if (bag.TryTake(out temp))
                    {
                        Console.Write(temp+",");
                        count++;
                    }
                }
                ));
            }
            Task.WaitAll(consumeTaskList.ToArray());
            Console.WriteLine();
            Console.WriteLine($"ConcurrentBag中元素个数{count}");
            int unexpectedItem;
            if (bag.TryTake(out unexpectedItem))
                Console.WriteLine($"ConcurrentBag中元素{unexpectedItem}");
        }

        public static  void ListTest()
        {
            List<int> list = new List<int>();
            List<Task> taskList = new List<Task>();
            for (int i = 0; i < 100; i++)
            {
                int numberToAdd = i;
                taskList.Add(Task.Run(() => list.Add(numberToAdd)));
            }
            Task.WaitAll(taskList.ToArray());


            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i]+",");
            }
            Console.WriteLine();
            Console.WriteLine($"list中元素个数{list.Count}");
            Console.WriteLine("--------------------------------");
        }
    }

 

List每次运行结果都不尽相同,体现了其多线程的不安全性

posted on 2022-04-20 11:15  张德长  阅读(113)  评论(0编辑  收藏  举报