最近在对博客园的程序进行性能优化,在优化过程中用到了Dictionary,在通过foreach将Dictionary中的数据写入数据库时,遇到了这样的错误:
Collection was modified; enumeration operation may not execute.
代码类似这样的:
// 添加数据操作省略
foreach (KeyValuePair < int , int > item in _dictionary)
{
}
在执行foreach时,其他线程对_dictionary进行了Add操作,改变了_dictionary中的数据,从而产生了上述的异常信息。
那什么会产生这样的异常信息呢?
但我们可以这样操作:
if (_ticketList.Count >= 1)
{
//get the expired ticket from the _ticketList
foreach (KeyValuePair<string, DateTime> i in _ticketList)
{
if (_now - i.Value <= _pointTime)
{
_needRemoveTicketList.Add(i.Key, i.Value);
//send email to the client
}
}
//remove the expired ticket from the _ticketList
foreach (KeyValuePair<string, DateTime> k in _needRemoveTicketList)
{
_ticketList.Remove(k.Key);
}
_needRemoveTicketList.Clear();
}
首先将要从_ticketList中要删除的元素存入另外一个dictionary 里。然后再循环把_ticketList中的元素删除。