chetan singhal
chetan singhal

Reputation: 948

Collection was modified; enumeration operation may not execute

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; 
                } 

Upvotes: 0

Views: 1398

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502816

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.

Upvotes: 3

Related Questions