我正在尝试制作一个GUI来与我的伺服驱动器进行交互。程序运行良好,没有任何编译错误,但在运行大约10到15秒后,我得到了我不知道的错误。
我读过几篇关于在C#中使用串口调用并避免其中的一些错误的文章。在阅读了这些帖子后,我遵循了他们关于如何使用的建议,但我仍然有问题。
我已经在github和 this is the link for github上传了我的程序。
下面是我的错误代码的快照。

当在线阅读寻找错误的原因时,我看到一些人说,对于他们来说,错误发生在代码的随机位置,但与他们不同的是,错误总是在ReadPort函数中,该函数在另一个线程中启动,而不是在主线程中处理。
发布于 2018-12-22 22:00:12
我不知道问题出在哪里,但我对SerialPortManager类中的ReadPort()方法进行了一些更改,如下所示,到目前为止,图形用户界面运行良好。
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中上传的代码相同
https://stackoverflow.com/questions/53895554
复制相似问题