المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Serial Port synchronous read



C# Programming
06-25-2009, 10:10 PM
I'm reading text from a SerialPort that begins and ends each message with a newline character. The following code causes the console to display the message:

while (port.BytesToRead == 0) ;
Console.WriteLine(port.ReadLine());
Console.WriteLine(port.ReadLine());


But this code causes the console to display nothing, and in fact the program hangs on the second ReadLine() :

while (port.BytesToRead == 0) ;
port.ReadLine();
Console.WriteLine(port.ReadLine());


It seems that some kind of delay (sleeping the thread for a few tenths of a second, writing anything to the console, even setting a break point!) is necessary to make consecutive ReadLine()s execute properly. My understanding of ReadLine() is that it blocks and waits until a newline character appears in the buffer, which is inconsistent with what I'm observing. I've even tried to just clear the first newline character with a Read() or ReadChar(), but the same problem occurs.

Note: the reads need to be synchronous because the serial port data affects my program's logic. I'm not just printing to console/textbox.