我正在读取Arduino,它通过USB端口发送文本。 Arduino每秒发送它的输出状态。在接收到的命令事件中,我设置了几个复选框(快门打开或电源打开,或点亮),并将收到的数据输出到多行文本框。 无论如何......这一切都有效,持续几秒钟,然后放慢速度,最终在大约10分钟后,我得到了一个Out of Memory异常。我不知道出了什么问题,我假设它在类中读取串行数据 - 所以这里是代码,任何人都可以看到错误吗?
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);
}
}
}
}
答案 0 :(得分:0)
这可能是由SerialPort类的实现引起的。它永远不会永远不会控制其他线程,因此终结线程无法完成对象并释放内存。请参阅我的文章:http://alexatnet.com/articles/net-memory-management-and-garbage-collector#best-practices
要解决此问题,您需要添加
Thread.CurrentThread.Join(100)
例如,它可能会添加到PortOnDataReceived
。这将允许终结线程运行等待终结器。