Wednesday, 21 August 2013

Collection was modified; enumeration operation may not execute. VB.Net

Collection was modified; enumeration operation may not execute. VB.Net

There are a lot of questions that are a duplicate of this question, but
none of them seem to actually answer my specific problem.
I am writing an IRC bot, and i am adding users to a List(Of String) as you
can see in the below code. However, when i want to go through a foreach
loop of the users on another thread, i get the error in the title. I have
even put a boolean in place to stop it from adding users, yet it still
says it is being modified somehow. Any help would be greatly appreciated.
(Before you read the code, keep in mind i am new to VB.net, and even if it
messy, i'd prefer to not be bashed for it as i am new)
Sub Handler()
handlerActive = True
Dim list As New List(Of String)
query = "SELECT * FROM " & channel.Substring(1)
Try
connHost.Close()
Catch
End Try
connHost.Open()
Dim cmd As MySqlCommand = New MySqlCommand(query, connHost)
Dim dataReader As MySqlDataReader = cmd.ExecuteReader()
While (dataReader.Read())
list.Add(dataReader.GetString(1))
End While
dataReader.Close()
If (users.Count > 0) Then
For Each user2 In users
Try
connHost.Close()
Catch ex As Exception
End Try
connHost.Open()
query = ("UPDATE `" & channel.Substring(1) & "` SET `Amount` =
Amount + 1 WHERE `Username`='" & user2 & "'")
cmd = New MySqlCommand(query, connHost)
Try
cmd.ExecuteNonQuery()
Catch
Console.WriteLine("Failed to update user - " & user2)
End Try
Next
End If
connHost.Close()
handlerActive = False
End Sub
Below here is where i add users to my List called "users"
If (handlerActive = False And users.Contains(user) = False And
user.Trim().CompareTo("") <> 0 Or user.Trim().CompareTo("jtv") <> 0 Or
user.Trim().Contains(" ") = False Or user.Trim().Contains(".") = False)
Then
users.Add(user)
End If

No comments:

Post a Comment