c# - 在 Debug 模式下获取正确值,在 Release 模式下使用串行编程获取错误值

标签 c# serial-port

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

RFID 在 Debug模式下发送的值是\n00200054476720D\r\n,但是当我在 Release模式下运行时,它会以小块的形式显示值,或者有时是一个空值,后跟该代码。

这是我的代码:

    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);
    }

最佳答案

Release模式代码运行“太快”——不幸的是它在 Debug模式下工作,因为行为没有明确定义:ReadExisting并不意味着 ReadEverythingEverToBeWritten。

[ReadExisting reads] all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.

考虑 ReadLine/ReadTo相反,它会阻塞直到读取正确的终止序列。

string indata = sp.ReadTo("\r\n");

关于c# - 在 Debug 模式下获取正确值,在 Release 模式下使用串行编程获取错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23397002/

相关文章:

c# - 为什么 C# 需要条件句周围的括号?

linux-kernel - 如何将串行端口设备驱动程序从 Linux 2.6.21 移植到 2.6.36?

java - Java RXTX 与 Arduino 串口通信

与 Char 数组合并的 C 结构

c# - Hangfire - 没有为此对象定义无参数构造函数

c# - 从 Powershell 获取 Azure Active Directory 访问 token

c# - 第一次机会异常(exception)

c# - 使用 Entity Framework 和 WCF 的大型应用程序

java - 串口读取 - 错误 : EXCEPTION_ACCESS_VIOLATION - C [rxtxSerial. dll+0x5b00]

c++ - 使用 C/C++ 在 Ubuntu 中查找 Arduino 连接到哪个 TTY 端口