如何在收到readLine时调用函数

时间:2012-05-24 14:04:26

标签: c# serial-port readline

我的程序需要通过serialport接收字符串。 问题是当没有输入时程序停留在ReadLine上。 有没有办法在SP.ReadLine读取一行时调用函数startReading?

void GetInput()
{
        SerialPort SP = new SerialPort();
        SP.PortName = "COM3";
        SP.Open();
        string Line = string.Empty;
        While(Line == "")
         {
                    Line = SP.ReadLine();
                    Application.DoEvents();
         }
          StartReading();
}

void StartReading()
{
}

1 个答案:

答案 0 :(得分:1)

    private void GetInput()
    {
        SerialPort SP = new SerialPort();
        SP.PortName = "COM3";
        SP.DataReceived += new SerialDataReceivedEventHandler(SP_DataReceived);
        SP.Open();
    }

    private void SP_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort serialPort = (SerialPort)sender;
        string line = serialPort.ReadLine();
        StartReading();
    }

    private void StartReading()
    {
    }