Results 1 to 3 of 3

Thread: [RESOLVED] Can't Enable A Timer In Another Thread

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jun 2010
    Posts
    177

    Resolved [RESOLVED] Can't Enable A Timer In Another Thread

    Hi, this should be an easy question for some of you. I can enable the timer TimerHighlightLEDs using the first part of the code below. However, it won't work with the second part of the code in red. I know this has something to do with the controls declared in the main thread, but I don't know how to fix it. Thanks.


    Code:
    Friend Class MainForm
        Private Sub ReadRptsBtn_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles ReadRptsBtn.Click
          'SOME CODE HERE
          TimerHighlightLEDs.Enabled = True
          TimerHighlightLEDs.Start()
          'SOME CODE HERE
        End Sub
    End Class
    
    Partial Class MainForm
        Private Sub ReadEngineMessages()
          'SOME CODE HERE
          TimerHighlightLEDs.Enabled = True
          TimerHighlightLEDs.Start()
          'SOME CODE HERE
        End Sub
    End Class

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: Can't Enable A Timer In Another Thread

    This is from the Remarks section of the documentation for the WinForms Timer class:
    This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
    You basically have to treat it like a control in that you only interact with it on the UI thread. That would mean marshaling a method call to the UI to start or stop the Timer if you are currently on a secondary thread. I suggest that you follow the CodeBank link in my signature below and check out my thread on Accessing Controls From Worker Threads to learn the ins and outs of that but, to cut a long story short, the simplest way to do that from code already in a form is like this:
    vb.net Code:
    1. BeginInvoke(Sub() TimerHighlightLEDs.Start())
    Note that there's no point calling Start or Stop as well as setting the Enabled property because they both do the same thing. Use the property if you're setting the state at design time or you're setting it at run time based on a calculated value. If you are hard-coding the value of the Enabled property then you should be calling the Start or Stop method instead.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Jun 2010
    Posts
    177

    Re: Can't Enable A Timer In Another Thread

    That worked. Thank you for your help.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width