如何妥善处理在课堂上使用的字节数组?(How do I properly dispose the b

2019-09-29 12:02发布

我有正被用来存储从客户端和服务器的数据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
    }

如何妥善处理这一类clearup由字节数组使用的内存? 在套接字通信正在使用的字节数组来存储发送/接收的消息。

Answer 1:

你只需要处置非托管内存。

在这种情况下,它看起来像你需要处理的唯一事情是Socket和可能ConnectionObject ,不管它是什么。

换句话说,处置的任何实例IDisposable ,这个类创建。

一旦这个对象超出范围的垃圾收集器会照顾的字节数组。



Answer 2:

你不(如@DrewNoakes描述接听)。 如果您发现这段代码特定部分作为对象创建/内存分配热点,考虑创建字节数组,从中可以租用一个已经分配的数组池。 一般来说,我尝试用服务器软件做到这一点所以有某种上限的内存使用情况。



文章来源: How do I properly dispose the byte array used in the class?