【发布时间】:2009-04-11 01:27:17
【问题描述】:
我正在测试一些同步结构,我注意到一些让我感到困惑的东西。当我枚举一个集合同时写入它时,它抛出了一个异常(这是预期的),但是当我使用 for 循环遍历集合时,它没有。有人可以解释一下吗?我认为 List 不允许读取器和写入器同时操作。我本来希望循环遍历集合会表现出与使用枚举器相同的行为。
更新:这是一个纯粹的学术练习。我知道如果同时写入列表,枚举列表是不好的。我也明白我需要一个同步构造。我的问题再次是关于为什么一个操作按预期抛出异常,而另一个却没有。
代码如下:
class Program
{
private static List<string> _collection = new List<string>();
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(AddItems), null);
System.Threading.Thread.Sleep(5000);
ThreadPool.QueueUserWorkItem(new WaitCallback(DisplayItems), null);
Console.ReadLine();
}
public static void AddItems(object state_)
{
for (int i = 1; i <= 50; i++)
{
_collection.Add(i.ToString());
Console.WriteLine("Adding " + i);
System.Threading.Thread.Sleep(150);
}
}
public static void DisplayItems(object state_)
{
// This will not throw an exception
//for (int i = 0; i < _collection.Count; i++)
//{
// Console.WriteLine("Reading " + _collection[i]);
// System.Threading.Thread.Sleep(150);
//}
// This will throw an exception
List<string>.Enumerator enumerator = _collection.GetEnumerator();
while (enumerator.MoveNext())
{
string value = enumerator.Current;
System.Threading.Thread.Sleep(150);
Console.WriteLine("Reading " + value);
}
}
}
【问题讨论】:
-
为什么使用 for 或 while 循环很重要? (不是想成为白痴,只是想知道)
-
区别不在于for和while。问题是在这两种情况下,我都是在写入集合时读取它,那么为什么行为会有所不同。
-
请看下面我的回答...
-
从所有 for/while 循环(包括 Add 循环)中删除 Thread.Sleep。你们看到不同的行为吗?
-
即使从循环中删除睡眠调用后,行为仍然存在。
标签: c# .net synchronization list enumerators