SessionBufferPool.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System.Collections.Concurrent;
  2. using XGame.Framework.Memory;
  3. namespace XGame.Framework.Network
  4. {
  5. public static class SessionBufferPool
  6. {
  7. private const int MAX_BUFFER_COUNT = 8;
  8. public const int BufferSize = 0x1000;
  9. private static ConcurrentQueue<byte[]> _sendBuffers = new ConcurrentQueue<byte[]>();
  10. static SessionBufferPool()
  11. {
  12. MemoryMonitor.Register(LowMemoryCallback);
  13. }
  14. private static void LowMemoryCallback()
  15. {
  16. _sendBuffers.Clear();
  17. }
  18. public static void Recycle(byte[] buffer)
  19. {
  20. if (buffer != null && _sendBuffers.Count < MAX_BUFFER_COUNT)
  21. {
  22. _sendBuffers.Enqueue(buffer);
  23. }
  24. }
  25. //在心跳和ProtobufHelper中获取 将由TCPRemote回收
  26. public static byte[] Acquire()
  27. {
  28. _sendBuffers.TryDequeue(out byte[] sendbuffer);
  29. return sendbuffer ?? new byte[BufferSize];
  30. }
  31. public static void Dispose()
  32. {
  33. _sendBuffers.Clear();
  34. }
  35. }
  36. }