Tyrael_Tian 2016-09-01 00:44 采纳率: 0%
浏览 1467
已结题

关于C#高性能Socket服务器SocketAsyncEventArgs的实现的一些疑问

// This class creates a single large buffer which can be divided up
// and assigned to SocketAsyncEventArgs objects for use with each
// socket I/O operation.

// This enables bufffers to be easily reused and guards against
// fragmenting heap memory.
//
// The operations exposed on the BufferManager class are not thread safe.
class BufferManager
{
int m_numBytes; // the total number of bytes controlled by the buffer pool
byte[] m_buffer; // the underlying byte array maintained by the Buffer Manager
Stack m_freeIndexPool; //
int m_currentIndex;
int m_bufferSize;

public BufferManager(int totalBytes, int bufferSize)
{
    m_numBytes = totalBytes;
    m_currentIndex = 0;
    m_bufferSize = bufferSize;
    m_freeIndexPool = new Stack<int>();
}

// Allocates buffer space used by the buffer pool
public void InitBuffer()
{
    // create one big large buffer and divide that 
    // out to each SocketAsyncEventArg object
    m_buffer = new byte[m_numBytes];
}

// Assigns a buffer from the buffer pool to the 
// specified SocketAsyncEventArgs object
//
// <returns>true if the buffer was successfully set, else false</returns>
public bool SetBuffer(SocketAsyncEventArgs args)
{

    if (m_freeIndexPool.Count > 0)
    {
        args.SetBuffer(m_buffer, m_freeIndexPool.Pop(), m_bufferSize);
    }
    else
    {
        if ((m_numBytes - m_bufferSize) < m_currentIndex)
        {
            return false;
        }
        args.SetBuffer(m_buffer, m_currentIndex, m_bufferSize);
        m_currentIndex += m_bufferSize;
    }
    return true;
}

// Removes the buffer from a SocketAsyncEventArg object.  
// This frees the buffer back to the buffer pool
public void FreeBuffer(SocketAsyncEventArgs args)
{
    m_freeIndexPool.Push(args.Offset);
    args.SetBuffer(null, 0, 0);
}

}

上面是MSDN官网给出的案例,在BufferManager类中有一个变量是 m_freeIndexPool,我看了很久这一段代码始终搞不明白这个变量存储的int集合代表的是什么意义,并且为什么在SetBuffer(SocketAsyncEventArgs args)方法中,m_freeIndexPool.Count > 0 就可以把接收到的数据放入m_buffer中?
MSDN官网:https://msdn.microsoft.com/zh-cn/library/bb517542.aspx

  • 写回答

1条回答 默认 最新

  • Tyrael_Tian 2016-09-03 05:26
    关注

    有大牛帮忙给解释一下吗?

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办