2011-08-27 49 views
0

我收到錯誤 收集已修改;枚舉操作可能不會執行。 在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; 
       } 

回答

2

看起來你已經得到了你正在閱讀,並從多個線程修改(對於不同的請求)的單個集合。首先,使用Queue並不安全 - 而且它的尤其是如果您在通過集合進行迭代而您在另一個集合中對其進行修改,則不是這樣。 (編輯:我剛剛注意到你甚至沒有使用泛型集合,如果你使用.NET 4,沒有理由使用非泛型集合......)

目前還不清楚你的「重新嘗試實現 - 你可能只能改變使用ConcurrentQueue<T>而不是,但你需要知道,當你迭代集合的時候,你讀取的值可能已經被取出另一個線程。

+0

是的,有多個請求在這個時候使用這個隊列。這並不總是發生。一天2-3次。我應該修改哪些代碼。 –

+1

@cpsinghal:使用鎖定或支持併發訪問的集合(如ConcurrentQueue) –

相關問題