0

I have a timer running every second, and I plan to have a check within every tick of that timer.

I have a hashtable which has two integers, the value I am trying to set as a time. Every time the timer ticks, it will add 1 to the value of whatever it was previously.

I have tried modifying the hashtable directly in my For each statement, that errors, I also tried creating a new hash table which stores the key and the new time that it will be, and after this set the values. But this gets an Object reference not set to an instance of an object, which isn't making sense as there is a check in place to ensure that it's not null.

Code

    Private Sub expiryTimer_Tick(sender As Object, e As EventArgs) Handles expiryTimer.Tick
    Dim toRemove As List(Of Integer)
    Dim toSet As Hashtable

    'Loop through active table
    If Active IsNot Nothing Then
        For Each key In Active
            If Active(key) >= 10 Then
                toRemove.Add(0)
            Else
                toSet.Add(key, Active(key) + 1)
            End If
        Next
    End If

    'Set Values
    If toSet IsNot Nothing Then
        For Each value In toSet
            Active(value) = toSet(value)
        Next
    End If

    'Remove Values
    If toRemove IsNot Nothing Then
        For Each value In toRemove
            Active.Remove(value)
        Next
        toRemove.Clear()
    End If


End Sub
Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). This is a pretty common mistake, you need to initialize your objects (ListOf & Hashtable) with `New`. – Trevor Jun 13 '18 at 12:35

1 Answers1

-1

You only have checks for "Active", not for these local vars

Dim toRemove As List(Of Integer)
Dim toSet As Hashtable

Try again with initialized vars

Dim toRemove As New List(Of Integer)
Dim toSet As New Hashtable
David Sdot
  • 2,343
  • 1
  • 20
  • 26
  • Yes thank you, that seemed to do it. I completely forgot about New. So that has fixed the error I was getting, but for some reason when the value hits 10, it is not removing it from the Hashtable? Do you have any ideas on why this may be? – Josh Allport Jun 13 '18 at 11:42
  • As this runs in a timer I think it could be a thread problem. Check for "ConcurrentDictionary", thats a threadsafe dictionary, that might help – David Sdot Jun 13 '18 at 12:16
  • For now you should mark this as answered and in case you still haveing problem with your hashtable, create a new question – David Sdot Jun 13 '18 at 12:17