qq_25834201
Tyrael_Tian
采纳率0%
2016-09-01 00:44 阅读 1.5k

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

1

// 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条回答 默认 最新

  • qq_25834201 Tyrael_Tian 2016-09-03 05:26

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

    点赞 评论 复制链接分享

相关推荐