我创建了一个软件,它从 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/