none
How do I change the value of a label with a timer without getting a "Cross-thread operation not valid" error RRS feed

  • Question

  • I'm trying to create a basic idle game like program in a visual studio form using visual basic, but every time that I try to run my program it gives me an error saying "System.InvalidOperationException: 'Cross-thread operation not valid: Control 'PointCounter' accessed from a thread other than the thread it was created on.'" I have the timer initialized when the form loads

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' initalizes timer
            TimerGameTick = New Timer(100)
    
            TimerGameTick.Enabled = True
    
            TimerGameTick.AutoReset = True
            TimerGameTick.Start()
    End Sub

    and I have an event set up for the timer

    Public Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)
            IntPoints = IntPoints + IntPointsPerSecond
            UpdateScore()
        End Sub

    and UpdateScore() is

    Public Sub UpdateScore()
            PointCounter.Text = "Click Points: " + IntPoints.ToString
        End Sub

    any Idea what I can do to fix this?

    Thursday, September 27, 2018 12:18 PM

Answers

  • Either switch to a System.Windows.Forms.Timer component, which will raise its event on the main thread, or modify your code to use a call to Invoke from the main form to execute the code that interacts with controls on the form.  e.g.

        Public Sub UpdateScore()
            Me.Invoke(Sub()
                          PointCounter.Text = "Click Points: " + IntPoints.ToString
                      End Sub)
        End Sub


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


    Thursday, September 27, 2018 12:37 PM
    Moderator

All replies

  • Either switch to a System.Windows.Forms.Timer component, which will raise its event on the main thread, or modify your code to use a call to Invoke from the main form to execute the code that interacts with controls on the form.  e.g.

        Public Sub UpdateScore()
            Me.Invoke(Sub()
                          PointCounter.Text = "Click Points: " + IntPoints.ToString
                      End Sub)
        End Sub


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


    Thursday, September 27, 2018 12:37 PM
    Moderator
  • Thanks
    Thursday, September 27, 2018 12:40 PM