您的位置:首页 > 编程语言 > C#

C# 中 HashTable在多线程环境中的遍历异常

2019-03-01 14:55 330 查看

C# 中 HashTable在多线程环境中的遍历异常

今天在工作中遍历Hashtable时遇到了一个问题,本来认为Hashtable是线程安全的,不会存在异常。偏偏在调试时,就抛出了这个异常。

现在就来看看这个异常。

测试代码:

class Program
{
static void Main(string[] args)
{
Hashtable hashtable = new Hashtable();  //创建Hashtable对象
for (int i = 0; i < 100; i++)  //先添加一些数据
{
hashtable.Add("key" + i, "object" + i);
}
Thread th = new Thread(Prnit);  //创建一条线程来遍历hashtable
th.IsBackground = true;
th.Start(hashtable);
Thread.Sleep(20);
for (int i = 100; i>0; i--) {    //主线程向hashtable中删除数据
hashtable.Remove("key"+i);
}
Console.ReadKey();
}
static private void Prnit(object o)
{
Hashtable hashtable = o as Hashtable;
while (true)
{
foreach (string str in hashtable.Values) //使用foreach来遍历hashtable
{
Console.WriteLine(str);
}
}
}
}

运行代码,抛出异常
System.InvalidOperationException:“集合已修改;可能无法执行枚举操作。”

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