【发布时间】:2012-06-07 09:24:31
【问题描述】:
我得到:
"collection was modified enumeration operation may not execute" at this line:
foreach (Message msg in queue)
过了一会儿。
我必须使用 .NET 2.0。
我对名为“queue”的私有List进行的两个操作如下:
// 1st function calls this
lock (queue)
{
queue.Add(msg);
}
// 2nd function calls this
lock (queue)
{
using (StreamWriter outfile = new StreamWriter("path", true)
{
foreach (Message msg in queue) // This is were I get the exception after a while)
{
outfile.WriteLine(JsonConvert.SerializeObject(msg));
}
queue = new List<Message>();
}
}
我做错了什么?
【问题讨论】:
-
我看不出有什么问题,但你为什么不简单地调用 queue.Clear() 而不是分配一个新的呢?这是我看到的唯一问题,即使我无法想象可能出了什么问题。
-
a:是否有任何其他操作与
queue通信,以及b:你为什么要重新分配queue? -
我同意这两个 cmets,如果您在释放锁之前重新分配队列,这似乎是未定义的行为。
-
哦,不。这是一个 O(n) 与一个 O(1)。我当然不希望这样,因为我不介意我已经迭代过的任何项目会发生什么。
-
@Brady 实际上是这样定义的:旧值已解锁
标签: c# multithreading list locking sync