SetBuffer socket

Examples

The following code example 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 buffers to be easily reused and guards against fragmenting heap memory.
C#

// 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<int> 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);
    }
}

Remarks

The offset and count parameters can't be negative numbers. The combination of the offset and count parameters must be in bounds of the data array in the buffer parameter.

This method sets the Buffer property to the buffer parameter, the Count property to the count parameter, and the Offset property to the offset parameter.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值