2

I am writing a class called Field which uses a serial object to get some values from an Arduino. I have an event being raised by the class (when data is received from the serial port, more or less) and when that happens I need to retrieve data from this class. The code below works, but doesn't seem to do so in the way I need it to. My knowledge of just how threading works is little to none, I just know that the serial port object runs in its own thread which makes working with it a massive pain.

Private Sub Field_eScore() Handles Field.eScore

    If InvokeRequired Then
        Invoke(Sub() lbl_COM_data.Text = Field.GetComData())
    Else
        lbl_COM_data.Text = Field.GetComData()
    End If

End Sub

Is there a way to easily access data operating in this other thread that doesn't involve having these “InvokeRequired” If-Then conditionals? Some more information on just how threading works in this case would be awesome too.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Paul Sites
  • 23
  • 3
  • Heres propably the answer: http://stackoverflow.com/questions/1360533/how-to-share-data-between-different-threads-in-c-sharp-using-aop and here are some good informations about threading: http://www.codeproject.com/Articles/26148/Beginners-Guide-to-Threading-in-NET-Part-1-of-n – Tearsdontfalls Nov 03 '12 at 13:34
  • Thanks for the reply, I like the document about threading, that's a cool set. Unfortunately the other stackoverflow reference isn't quite what I'm looking for. – Paul Sites Nov 03 '12 at 17:36
  • You shouldn't replicate code like that. The Invoke could call itself. – the_lotus May 25 '17 at 15:42

1 Answers1

0

InvokeRequired is required because the UI can only be modified by the thread that created the controls (normally the main thread).

To "avoid" it, design your code to separate the responsibilities -- keep UI modification in a different layer from code dealing with serial port.

You'll still need to check if InvokeRequired in some places -- where you do interface your backend with the UI -- but it should be only in one "layer".

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101