在调试模式下获取正确的值,在使用串行编程的释放模式下出错

Moh*_*sin 2 c# serial-port

我创建了一个软件,它从RFID标签读取值,并通过串行端口连接到计算机.当我在调试模式下运行程序时,会收到正确的值,但是当我在发布模式下运行它时会显示一个不同的值.

RFID在调试模式下发送的值是\n00200054476720D\r\n,但是当我在发布模式下运行时,它以小块显示值,或者有时显示空值后跟该代码.

这是我的代码:

    try
    {
         _port2.PortName = "COM" + doorport_txt.Text;
         _port2.BaudRate = 9600;
         _port2.Parity = Parity.None;
         _port2.DataBits = 8;
         _port2.StopBits = StopBits.One;
         _port2.DataReceived += DoorPortDataReceivedHandler;
         _port2.ReadTimeout = 2000;
         if (!_port2.IsOpen)
    {
         _port2.Open();
    }
    MessageBox.Show(@"Door Port is Ready", @"Information", MessageBoxButtons.OK, 
MessageBoxIcon.Information);
    }
        catch (Exception ex)
        {
        MessageBox.Show(ex.Message, @"Error", MessageBoxButtons.OK,
     MessageBoxIcon.Error);
        }

    private void DoorPortDataReceivedHandler(object sender, 
SerialDataReceivedEventArgs e)
    {
        var sp = (SerialPort) sender;
        string indata = sp.ReadExisting();
        CheckTheft(indata);
    }
Run Code Online (Sandbox Code Playgroud)

use*_*740 5

发布模式代码运行"太快" - 不幸的是它在调试模式下运行,因为行为没有很好地定义:ReadExisting并不意味着ReadEverythingEverToBeWritten.

[ReadExisting读取] 基于编码的所有立即可用字节,在SerialPort对象的流和输入缓冲区中.

请考虑使用ReadLine/ReadTo,直到读取正确的终止序列为止.

string indata = sp.ReadTo("\r\n");
Run Code Online (Sandbox Code Playgroud)