Click here to Skip to main content
15,064,026 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello,
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,
Glev.
[edit]Code block added - OriginalGriff[/edit]
[edit]Added additional information[/edit]
Moved from OP's "solution":
I'm looking for the cause for the difference between regular timer and Threading.Timer, when I read data from the port with regular timer everything is ok, when I change it to Threading.Timer then I get no data.

BTW, in order to get data from my device I need to write a request, I write a request and immediately get response with data.
Posted
Updated 9-Mar-11 4:00am
v3
Comments
Albin Abel 9-Mar-11 6:00am
   
Look for serail port events. Timer tick can't be synchronize with device output

1 solution

Without seeing the code you are actually using, it is difficult to work out what is happening. However, it may be worth you changing from Timer based serial port to event based: Handle the SerialPort.DataReceived event instead of doing it every x ms.

The File/SerialPort difference could be anything: a bad physical loopback on the serial port, to code problems, to you assuming that serial data is "always there": without code, it is not possible to be accurate!
   
Comments
   
Of course, all the attempts of using timers should be trashed whenever possible (and most usually it is possible; some exclusions apply), my 5,
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900