【发布时间】:2015-10-30 20:18:10
【问题描述】:
早上好,
我正在开发一个 C# WPF 应用程序,该应用程序从 DATALOGIC 扫描仪 (DS4800-1000) 连续读取条形码(大约每分钟一个)并将它们发送到服务器,该服务器回复有关该特定条形码的详细信息。此扫描仪通过 MOXA(UPort 1100 型号)的 USB 转串口转换器连接到运行 Windows 8.1(非 RT)的平板电脑。
每当读取新条形码时,都会触发 DataReceived 事件并使用以下方法进行处理:
private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Log.log(Log.LogLevel.Info, "MainScreen.port1_DataReceived");
Thread.Sleep(100);
String data = "";
// If the com port has been closed, do nothing
if (!comport1.IsOpen)
{
Log.log(Log.LogLevel.Info, "MainScreen.port1_DataReceived - COM CLOSED");
data = "COM CLOSED"; // Must be < 16 chars
}
else
{
// Obtain the number of bytes waiting in the port's buffer
int bytes = comport1.BytesToRead;
// Create a byte array buffer to hold the incoming data
byte[] buffer = new byte[bytes];
// Read the data from the port and store it in our buffer
comport1.Read(buffer, 0, bytes);
data = Encoding.Default.GetString(buffer);
Log.log(Log.LogLevel.Info, "Data received from barcode scanner number 1: " + data);
}
// COM port is handled by a different thread; this.Dispatcher calls the original thread
this.Dispatcher.Invoke((Action)(() =>
{
ExtractBarcodeData(data);
} ));
}
我观察到一个奇怪的行为:在随机时间,我看到应用程序根本没有反应,尽管扫描仪实际上读取了一个新的条形码,而我希望一个新的 DataReceived 事件与以前的条形码一样。日志告诉我该端口实际上是打开的,我也可以使用一个特定的按钮来关闭它,该按钮关闭并重新打开它。这里出现异常(在 Open() 调用上):连接到系统的设备无法正常工作。
我无法重现此错误,它完全不可预测且随机!有人知道为什么 DataReceived 事件没有触发吗?
谢谢, FZ
【问题讨论】:
标签: c# wpf serial-port