码迷,mamicode.com
首页 > 编程语言 > 详细

多线程下的for循环和foreach循环 System.InvalidOperationException: 集合已修改;可能无法执行枚举

时间:2015-01-13 14:30:16      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:system.invalidoperat   c#   多线程   线程安全   

背景:当循环体在循环的时候有需求要修改自己。或者在多线程下,循环静态变量的时候,别人很容易修改了循环体内的数据。但是这就会报错的

准备:for;foeach;多线程。

解决方案:For循环是线程安全的,foreach是线程不安全的。说起开好像很高大上哈。意思是在循环内如,如果调用他们自己的循环体。前者是可以的,但是后者是不行的。

再者如果你循环的是字典。字典是键值对的形式,所以采用线程安全的字典ConcurrentDictionary的字典也可以一定程度的解决问题。但是做好的方案还是添加锁

1,用for

2,用安全集合

3,用锁(最安全但是影响性能)

代码结果展示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ForAndForeach
{
    class Program
    {
        
        static void Main(string[] args)
        {
            //整型列表
            List<int> listInt = new List<int>();
            listInt.Add(0);
            listInt.Add(1);
            listInt.Add(2);
            listInt.Add(3);
            listInt.Add(4);
            listInt.Add(5);
            //for循环调用自己
            for (int i = 0; i < listInt.Count; i++) {
                Console.WriteLine("for:"+listInt[i]);
                listInt.Add(6);
                if (i == 6)
                {
                    break;
                }
            }
            //foreach循环调用自己
            foreach (int i in listInt) {
                Console.WriteLine("foreach:"+i);
                listInt.Add(7);
                if (i == 7) {
                    break;
                }
            }
            
        }
    }
}
技术分享

多线程下的for循环和foreach循环 System.InvalidOperationException: 集合已修改;可能无法执行枚举

标签:system.invalidoperat   c#   多线程   线程安全   

原文地址:http://blog.csdn.net/shuanger_/article/details/42674635

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!