简体   繁体   English

DataReceived EventHandler仅工作一次

[英]DataReceived EventHandler works only once

I am new to stackoverflow. 我是stackoverflow的新手。 I am having a problem with VC# Serial Communication. VC#串行通讯出现问题。 I need t receive data conyinuously from serial port but my code works only once. 我不需要从串行端口连续接收数据,但是我的代码只能运行一次。 That is if I send "This is a Serial Comm Project". 那就是如果我发送“这是一个串行通信项目”。 The data is received as expected but if I send the data again it doesn't work. 数据已按预期接收,但是如果我再次发送数据,它将无法正常工作。 Please provide a solution. 请提供解决方案。

private void button1_Click(object sender, EventArgs e)
{

        mySerialPort.PortName = cbxCOMPort.Text;
        mySerialPort.BaudRate = int.Parse(cbxBaudrate.Text);
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.RequestToSend;
        mySerialPort.ReadTimeout = int.Parse(cbxTimeout.Text);
        mySerialPort.WriteTimeout = 2000;
        mySerialPort.DtrEnable = true;
        mySerialPort.RtsEnable = true;
        mySerialPort.Encoding = Encoding.ASCII;
        mySerialPort.NewLine = "\r\n";
        mySerialPort.ReadBufferSize = 512;

        mySerialPort.DataReceived += port_DataReceived;

        mySerialPort.Open();

        button1.Enabled = false;
        button2.Enabled = true;
        gbxMsgDel.Enabled = true;

}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{// Event for receiving data

        // Read the buffer to text box.

        this.Invoke(new EventHandler(DoUpdate));

}

private void DoUpdate(object s, EventArgs e)
{
        receivedMessage += mySerialPort.ReadExisting();

}

receivedMessage is a private string type. receiveMessage是私有字符串类型。 It is private to the class. 它是班上私人的。

I had a similar problem before... 我之前也有类似的问题...

From MSDN 从MSDN

"The DataReceived event is not guaranteed to be raised for every byte received" “不能保证收到的每个字节都会引发DataReceived事件”

One option is to use a timer to check available data instead of the event, something like this: 一种选择是使用计时器而不是事件来检查可用数据,如下所示:

private void checkPortDataTimer_Tick(object sender, EventArgs e)
{
    //You may want to check available bytes instead of this.
    string recievedData = comPort.ReadExisting();
    if (!string.IsNullOrEmpty(recievedData))
        someTextBox.Text += recievedData;
}

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM