如何正确处理类中使用的字节数组?

时间:2012-10-23 15:14:16

标签: c# .net sockets memory-leaks

我有一个StateObject类,用于存储来自客户端和服务器的数据。

以下是代码:

 public class StateObject : IDisposable 
    {
        public StateObject()
        {

        }

        public String serviceName = ConfigurationManager.AppSettings["ServiceName"].ToString().Trim();  //Holds the service name 
        public Socket clientSocket; //socket for communication with the client

        public int id; //client id  (A running sequence to keep track of StateObjects)

        public string leaseId; //holds the leaseId that is used to communicate with the server

        public bool isLeaseIdValid = false;

        public string requestQuery = string.Empty;

        public IPEndPoint serverEP;

        public Socket serverSocket; //Socket for communication with the server

        public static int BUFFER_SIZE = Convert.ToInt32(ConfigurationManager.AppSettings["BufferSize"].ToString().Trim());  //Get the buffer size from the state object

        public byte[] clientReadBuffer = new byte[BUFFER_SIZE];   // Receive clientReadBuffer.
        public byte[] serverReadBuffer = new byte[BUFFER_SIZE];

        public int clientNumBytes;
        public byte[] clientSendBuffer = new byte[BUFFER_SIZE];
        public int serverNumBytes;
        public byte[] serverSendBuffer = new byte[BUFFER_SIZE];

        public bool isShutdown = false;

        public Socket serverSocketPort80; //Socket for communication with the server

        public bool ConnectedToPort80 = false; //initially set to false

        public ConnectionObject connectionObject;

        #region Dispose implementation

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                connectionObject.Dispose();
            }
        }

        ~StateObject()
        {
            Dispose(false);
        }

        #endregion
    }

如何正确处理此类并清除字节数组使用的内存?字节数组用于在套接字通信中存储发送/接收的消息。

2 个答案:

答案 0 :(得分:7)

您只需要处理非托管内存。

在这种情况下,您需要处理的唯一事情是Socket,可能还有ConnectionObject,无论是什么。

换句话说,配置此类创建的IDisposable的任何实例。

一旦此对象超出范围,垃圾收集器将处理字节数组。

答案 1 :(得分:5)

你没有(如@DrewNoakes回答中所述)。如果将此特定代码段标识为对象创建/内存分配热点,请考虑创建一个字节数组池,您可以从中租用已分配的数组。一般来说,我尝试用服务器软件做这个,所以内存使用有一些上限。