开发者

Reading from the serial port with the DataReceived event

I have a Visual Studio 2008 C# .net 2.0 CF application that reads from a serial port using the System.IO.Ports.SerialPort class. Unfortunately, the SerialDataReceivedEventHandler is never called.

I open the port like this:

private SerialPort serial_port_;
protected void OpenSerialPort(string port, int baud)
{
    if (serial_port_ == null)
    {
        serial_port_ = new SerialPort(port,
                                  baud,
                                  Parity.None,
                                  8,
                                  StopBits.One);
    }
    else
    {
        serial_port_.BaudRate = baud;
        serial_port_.PortName = port;
    }

    if (!serial_port_.IsOpen)
    {
        ser开发者_高级运维ial_port_.Open();
        serial_port_.DataReceived += new SerialDataReceivedEventHandler(OnSerialDataReceived);
    }
}

private void OnSerialDataReceived(object sender, SerialDataReceivedEventArgs args)
{
    Debug.WriteLine("Serial data received");
}

If, however, I add a Debug.WriteLine(serial_port_.ReadLine()); right after the port is opened, I see in the output window a line of text from the port just as I would expect.

So, why does ReadLine work, but the DataReceived event does not?

Thanks, PaulH


Edit: Further testing shows this code works on some devices, but not others. What does the DataReceived event require to work properly?

Further Frustration: On this device, ReadExisting always returns null and BytesToRead always returns 0. ReadLine() and Read() both work perfectly, though.


Don't put blocking reads in the data received handler. If the handler fires and there is NOT an entire line to be read it will block. In the code you posted there is not a read of any kind.

From MSDN: "PinChanged , DataReceived, and ErrorReceived events may be called out of order, and there may be a slight delay between when the underlying stream reports the error and when the event handler is executed. Only one event handler can execute at a time."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜