0

我正在阅读 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);
        }
    }
}

}

4

1 回答 1

0

这可能是由 SerialPort 类的实现引起的。它可能永远不会将控制权交给其他线程,因此终结线程无法终结对象并释放内存。请参阅我的文章:http ://alexatnet.com/articles/net-memory-management-and-garbage-collector#best-practices

要修复它,您需要添加

Thread.CurrentThread.Join(100)

例如,它可以添加到PortOnDataReceived. 这将允许终结线程运行挂起的终结器。

于 2013-11-01T03:10:33.497 回答