0
我正在通過USB端口發送文本的Arduino正在讀取數據。 Arduino每秒發送一次輸出的狀態。在命令接收事件中,我設置了幾個複選框(快門打開或電源開啓,或點亮),並將其收到的數據輸出到多行文本框。
無論如何....它的所有工作,幾秒鐘,然後減慢,最終約10分鐘後,我得到一個內存不足的例外。我無法弄清楚什麼是錯誤的,我假設它在讀取串行數據的類中 - 所以這裏是代碼,任何人都可以看到任何錯誤?Serial.readline - 內存不足
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);
}
}
}
}
向我們展示您附加到'CommandReceived'的位置以及響應它的方法。 –
你是否試圖找到你在哪裏收到這個異常。我的意思是在哪一行? – Tariq
這可能是一個平臺錯誤。串行驅動程序代碼可能會在某個時刻使用未經初始化的指針。您可以嘗試在try/catch塊中包含ReadLine()並忽略OOM異常? – Mac