Question

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

Was it helpful?

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.

OTHER TIPS

If you catch the SerialPort.DataReceived event and then use wither SerialPort.ReadLine or SerialPort.Read(byte[],int,int) those methods will be executed on a new thread. I prefer to use a mutex to control access to the buffer of bytes as a shared resource. Also have you ever communicated with your device successfully? If not in addition to the port setting check the SerialPort.NewLine property and the SerialPort.Handshake property. These settings vary depending on the device you are trying to communicate with.

Why do you use it to begin with?

Have a look at this pages, it might give you a direction

  1. My favorite: Is DoEvents Evil?
  2. From msdn blog Keeping your UI Responsive and the Dangers of Application.DoEvents
  3. From msdn forums Application does not return from call to DoEvents

Without code, it'll be hard to help. Even with code, it might be hard to help :)

I'm agreeing with gunr2171 on this :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top