Search code examples
c#multithreadingserial-portdoevents

multi-threading safe usage with SerialPort controller


I have read dozens of articles about threading in c# and Application.DoEvents() ... Still can't use it properly to get my task done: I have a controller connected to my COM, this controller works on command (i send command, need to wait few ms to get response from it), assume the response is a data that i want to plot every time interval using a loop:

  • start my loop.
  • send command to controller via serialPort.
    • wait for response (wait let say 20 ms).
    • obtain data.
  • repeat this loop every let say 100 ms.

this simply doesn't want to work!! i tried to communicate with the data controller on other thread but it seems that it can't access the serialPort which belongs to the main thread (roughly speaking).

any help is appreciated


Solution

  • Application.DoEvents is for all it does - nothing more than a nested call to a windows (low level) message loop on the same thread. Which might easily cause recursion if you call it in in an event handler. You might consider creating your serial port object on the worker thread and communicate through threading classes (i.e. the WaitHandles and similar). Or call back to your UI thread using "BeginInvoke" and "EndInvoke" on the UI object.