我正在阅读 Arduino,它通过 USB 端口发送文本。Arduino 每秒发送一次它的输出状态。在收到的命令事件中,我设置了几个复选框(快门打开或电源打开,或灯打开),并将接收到的数据输出到多行文本框。
无论如何....一切正常,几秒钟,然后放慢速度,最终在大约 10 分钟后我得到了内存不足的异常。我不知道出了什么问题,我假设它在读取串行数据的类中 - 所以这是代码,有人能看出什么问题吗?
using System;
using System.IO.Ports;
namespace WOCA.Core.SerialComms
{
internal class ArduinoCommunicator : ICommunicator
{
public event EventHandler<CommsEventsArg> CommandReceived;
internal ArduinoCommunicator(string comPort)
{
Port = new SerialPort(comPort) {BaudRate = 9600, DtrEnable = true};
Port.DataReceived += PortOnDataReceived;
}
private SerialPort Port { get; set; }
public bool IsOpen { get; set; }
public void Open()
{
try
{
if (!Port.IsOpen)
{
Port.Open();
IsOpen = true;
}
else
{
throw new InvalidSerialCommsException("Serial port already open");
}
}
catch (Exception ex)
{
throw new InvalidSerialCommsException("Serial Port error: " + ex.Message);
}
}
public void Close()
{
try
{
if (Port.IsOpen)
{
Port.Close();
IsOpen = false;
}
else
{
throw new InvalidSerialCommsException("Serial port not open");
}
}
catch (Exception)
{
throw new InvalidSerialCommsException("Serial port error");
}
}
public void SendCommand(string command)
{
try
{
if (Port.IsOpen)
{
Port.Write(command);
}
else
{
throw new InvalidSerialCommsException("Serial port not open");
}
}
catch (Exception)
{
throw new InvalidSerialCommsException("Serial port error, the command has not been sent");
}
}
private void PortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
SerialPort serialPort = sender as SerialPort;
if (serialPort != null)
{
string command = serialPort.ReadLine();
command = command.Remove(command.Length-1,1);
CommsEventsArg args = new CommsEventsArg(command);
OnCommandReceived(args);
}
}
protected virtual void OnCommandReceived(CommsEventsArg e)
{
EventHandler<CommsEventsArg> handler = CommandReceived;
if (handler != null)
{
handler(this, e);
}
}
}
}