我正在尝试使GUI与我的伺服驱动器进行交互。该程序运行良好,没有任何编译错误,但是在运行10到15秒后,我得到了一个我不知道的错误。
我已经阅读了几篇有关在C#中使用串行端口调用的文章,并避免了其中的一些错误。阅读这些帖子后,我遵循了他们的使用建议,但仍然有问题。
我已经在github和 this is the link for github中上传了程序(GUI)。
下面是我的错误代码的快照。
在在线阅读以查找错误原因时,我看到有人说对于他们来说,错误发生在他们代码的随机位置,但与他们不同的是,错误始终在ReadPort函数中,该函数在另一个线程而不是main中启动
答案 0 :(得分:0)
我不知道问题出在哪里,但是我在SerialPortManager类中的ReadPort()方法中做了一些更改,如下所示,并且GUI到目前为止运行良好。
public void ReadPort()
{
string ReceivedMessage = "No Message";
if (_serialPort == null)
{
return;
}
while (_keepReading)
{
List<byte> receiveBuffer = new List<byte>();
int bytesToRead = _serialPort.BytesToRead;
byte[] tempBuffer = new byte[bytesToRead];
_serialPort.Read(tempBuffer, 0, bytesToRead);
receiveBuffer.AddRange(tempBuffer);
ReceivedMessage = _serialPort.Encoding.GetString(receiveBuffer.ToArray());
if (OnDataReceived != null)
OnDataReceived(this, ReceivedMessage);
}
}
其余代码与github中上载的代码相同