C# 使用ConcurrentBag类处理集合线程安全问题

以下代码,使用List<T>会遇到问题:

System.InvalidOperationException:“集合已修改;可能无法执行枚举操作。”

    class Program
    {
        private static List<string> list = new List<string>();

        static void Main(string[] args)
        {
            var count = 0;

            //任务一
            Timer timer1 = new Timer((obj) =>
            {
                var str = "a" + ++count;
                list.Add(str);
                Console.WriteLine("添加了:" +str);
            }, null, 0, 1000);

            //任务二
            Timer timer2 = new Timer((obj) =>
            {
                foreach (var item in list)
                {
                    Console.WriteLine("显示:" + item);
                }
            }, null, 0, 1000);

            Console.ReadLine();
        }
    }

改成:ConcurrentBag<T>就不会了,因为ConcurrentBag<T>是线程安全的。

   class Program
    {
        private static ConcurrentBag<string> list = new ConcurrentBag<string>();

        static void Main(string[] args)
        {
            var count = 0;

            //任务一
            Timer timer1 = new Timer((obj) =>
            {
                var str = "a" + ++count;
                list.Add(str);
                Console.WriteLine("添加了:" +str);
            }, null, 0, 1000);

            //任务二
            Timer timer2 = new Timer((obj) =>
            {
                foreach (var item in list)
                {
                    Console.WriteLine("显示:" + item);
                }
            }, null, 0, 1000);

            //任务三
            Timer timer3 = new Timer((obj) =>
            {
                foreach (var item in list)
                {
                    Console.WriteLine("删除了:" +item);
                    list.TryTake(out string result);
                }
            }, null, 0, 3000);

            Console.ReadLine();
        }
    }

 参考网址:https://blog.csdn.net/boonya/article/details/80541460

猜你喜欢

转载自www.cnblogs.com/subendong/p/11841906.html
今日推荐