17 octobre 2007

Collection was modified; enumeration operation may not execute.

If we want to change a value in a Hashtable, there is a problem with the Foreach loop:
Hashtable MyHt=new Hashtable();
MyHt.Add("my key", "my value");
.....

foreach (DictionaryEntry entry in MyHt)
{
MyHt[entry.Key] = "my value";
}
The is the error message :
"Collection was modified; enumeration operation may not execute."

So for resolve this, we juste do an
ArrayList arrayList = new ArrayList(((Hashtable)Application[AppName]).Keys);
IEnumerator listEnumerator = arrayList.GetEnumerator();
while (listEnumerator.MoveNext())
{
((Hashtable)Application[AppName])[Session.SessionID.ToString()] = DateTime.Now.AddMinutes(10);
Hashtable ht = (Hashtable)Application[AppName];
DateTime dateOfSession = Convert.ToDateTime(ht[listEnumerator.Current].ToString());
if (dateOfSession.CompareTo(DateTime.Now) < 0)
{
((Hashtable)Application[AppName]).Remove(Session.SessionID.ToString());
}
}

Aucun commentaire: