Why does enumerating through a collection throw an exception but looping through its items does not(为什么通过集合枚举会引发异常但遍历其项目不会)
问题描述
我正在测试一些同步结构,我注意到一些让我感到困惑的东西.当我枚举一个集合同时写入它时,它抛出了一个异常(这是预期的),但是当我使用 for 循环遍历集合时,它没有.有人可以解释一下吗?我认为 List 不允许读取器和写入器同时操作.我本来希望循环遍历集合会表现出与使用枚举器相同的行为.
I was testing out some synchronization constructs and I noticed something that confused me. When I was enumerating through a collection while writing to it at the same time, it threw an exception (this was expected), but when I looped through the collection using a for loop, it did not. Can someone explain this? I thought that a List does not allow a reader and writer to operate at the same time. I would have expected looping through the collection to exhibit the same behavior as using an enumerator.
更新:这是一个纯粹的学术练习.我知道如果同时写入列表,枚举列表是不好的.我也明白我需要一个同步构造.我的问题再次是关于为什么一个操作按预期抛出异常,而另一个却没有.
代码如下:
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);
/
本文标题为:为什么通过集合枚举会引发异常但遍历其项目不会
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01