您的位置:首页 > 运维架构

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

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

准备: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;
}
}

}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息