背景:當循環體在循環的時候有需求要修改自己。或者在多線程下,循環靜態變量的時候,別人很容易修改了循環體內的數據。但是這就會報錯的
準備: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;
}
}
}
}
}