集合已修改;枚举操作可能无法执行
我遇到错误 集合已修改;枚举操作可能无法执行。 在 System.Collections.Queue.QueueEnumerator.MoveNext()
Queue ReqQ = (Application["ReqQ"] != null) ? ((Queue)Application["ReqQ"]) :
new Queue(50);
if (ReqQ != null)
{
foreach (object OReq in ReqQ)
{
string mId = (string)OReq;
if (mId.Split('~')[1].Equals(reqUid.Split('~')[1]) && (DateTime.Parse(mId.Split('~')[0]).AddMinutes(1 * int.Parse(string.IsNullOrEmpty(delay) ? "0" : delay)) > DateTime.Now))
{
isSuccess = false;
break;
}
}
}
else
{
ReqQ = new Queue(10);
isSuccess = true;
}
if (isSuccess)
{
if (ReqQ.Count >= 10) //only keep last 10 messages in application cache
ReqQ.Dequeue();
ReqQ.Enqueue(reqUid);
Application["ReqQ"] = ReqQ;
}
I have getting error
Collection was modified; enumeration operation may not execute.
at System.Collections.Queue.QueueEnumerator.MoveNext()
Queue ReqQ = (Application["ReqQ"] != null) ? ((Queue)Application["ReqQ"]) :
new Queue(50);
if (ReqQ != null)
{
foreach (object OReq in ReqQ)
{
string mId = (string)OReq;
if (mId.Split('~')[1].Equals(reqUid.Split('~')[1]) && (DateTime.Parse(mId.Split('~')[0]).AddMinutes(1 * int.Parse(string.IsNullOrEmpty(delay) ? "0" : delay)) > DateTime.Now))
{
isSuccess = false;
break;
}
}
}
else
{
ReqQ = new Queue(10);
isSuccess = true;
}
if (isSuccess)
{
if (ReqQ.Count >= 10) //only keep last 10 messages in application cache
ReqQ.Dequeue();
ReqQ.Enqueue(reqUid);
Application["ReqQ"] = ReqQ;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您有一个正在从多个线程(针对不同请求)读取和修改的单个集合。首先,使用
Queue
并不安全 - 如果您在另一个集合中修改集合时迭代该集合,则尤其如此。 (编辑:我刚刚注意到您甚至没有使用通用集合。如果您使用.NET 4,则没有理由使用非通用集合...)目前尚不清楚您想要实现什么目标- 您可能只需更改为使用
ConcurrentQueue
相反,但您需要注意,当您迭代集合时,您读取的值可能已经出队在另一个线程中。It looks like you've got a single collection which you're reading and modifying from multiple threads (for different requests). To start with that's not safe using
Queue
- and it's particularly not true if you're iterating through the collection while you modify it in another. (EDIT: I've just noticed you're not even using a generic collection. If you're using .NET 4, there's no reason to use the non-generic collections...)It's unclear what you're trying to achieve - you may be able to get away with just changing to use
ConcurrentQueue<T>
instead, but you need to be aware that by the time you've iterated over the collection, the values you read may already have been dequeued in another thread.