List that this enumerator is bound to has been modified

好久不见. 提交于 2019-12-11 01:31:52

问题


I have this bit of code here, and at the next statement it's giving me an error saying:

List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

I really don't know how to further explain this issue, but if you need me to I can try.

For Each itemChecked In storedAuthorsListbox.CheckedItems
  Dim selectedAuthor As String = storedAuthorsListbox.SelectedItem.ToString()
  Dim authorFile As String = "Authors\" & itemChecked.ToString()
  Dim document As XmlReader = New XmlTextReader(authorFile)

  metaInfo &= "[Author]" & vbNewLine

  While (document.Read())
    Dim type = document.NodeType
    If (type = XmlNodeType.Element) Then
      If (document.Name = "Name") Then
        metaInfo &= "Name=" & document.ReadInnerXml.ToString() & vbNewLine
      ElseIf (document.Name = "Website") Then
        metaInfo &= "Website=" & document.ReadInnerXml.ToString() & vbNewLine
      ElseIf (document.Name = "Notes") Then
        metaInfo &= "Notes=" & document.ReadInnerXml.ToString() & vbNewLine
      End If
    End If
  End While
  document.Close()
Next

回答1:


Some code somewhere is changing storedAuthorsListbox while you are iterating it. That code is not visible in the snippet. Do make sure that the posted code is not running in a worker thread, that is not legal. It certainly quacks like the kind of code you'd run in a worker.

The generic solution is to make a copy of the items and work from that copy instead of the control:

    Dim copy = storedAuthorsListBox.SelectedItems.OfType(Of String)().ToList()
    For Each itemchecked In copy
        '' etc..
    Next

If this runs in a worker thread then pass the copy to the worker.



来源:https://stackoverflow.com/questions/18947629/list-that-this-enumerator-is-bound-to-has-been-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!