Reputation: 11
My application reads every x ms some data from a serial port(MyDataReader) and displays it on a control, MyDataReader also can be a file, from which I can read data.
I used a simple timer, every tick I've read the data from the serial port/file, processed it and displayed it, It worked great.
Now I've added another device from which I need to read data and I've switched to System.Threading.Timer, but now my "tick" function is not working properly, when it reads from the serial port, I get zeros. when I enter debug mode and breakpoint ReadFromSerialPort() function, sometimes I get valid data, sometimes I don't.
If I switch the reading from serialport to read from file it works fine, I've invoked all the controls that display data.
I locked the read/write from the serialport:
lock(this)
{
writetoserialport;
readfromserialport;
}
anyone have any idea why I get zeros all the time, and when I breakpoint I have sometimes data? It's like it opens the read from serial port on different thread and I need to wait to the data to be read.
Thank you.
Upvotes: 1
Views: 1657
Reputation: 1092
Well, a serial port is not the same as a file.
The file data is stored on disk and if the file is not truncated, you can get it later. Data can come from serial port and may not be captured.
So you must capture data from the serial port and store it in a buffer. Then the timer will get data from your buffer.
If this is not your problem, tell us more.
Upvotes: 1
Reputation: 812
Reading for a serial port is not deterministic. At the moment you are executing the read function, there may not be data in the port. Are you checking if there is data to be read before actually executing the read function?
In case of putting in breakpoint, because the speed of debugging varies, you sometimes see data.
Upvotes: 0