BytesWrapper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System.Collections.Concurrent;
  2. namespace XGame.Framework.Network
  3. {
  4. public class BytesWrapper
  5. {
  6. public byte[] buffer;
  7. public int offset;
  8. public int size;
  9. public BytesWrapper(byte[] buffer, int offset, int size)
  10. {
  11. this.buffer = buffer;
  12. this.offset = offset;
  13. this.size = size;
  14. }
  15. }
  16. public static class BytesWrapperPool
  17. {
  18. private const int MAX_BUFFER_COUNT = 8;
  19. private static ConcurrentQueue<BytesWrapper> bytesWrappers = new ConcurrentQueue<BytesWrapper>();
  20. //ProtobufHelper Recycle->Tpro2Sender /ProtobufSender
  21. //ZstdCompress Recycle->Tpro2Sender /----------------(tpro1发送不压缩)
  22. //ZstdDecompress Recycle->TPro2MsgResolver /TProMsgResolver
  23. //RC4Encrypt Recycle->TPro2Sender /----------------(tpro1发送不加密)
  24. //RC4Dencrypt Recycle->TPro2MsgResolver /----------------(tpro1接收不解密)
  25. //TProMsgResolver Recycle->TProMsgResolver
  26. //TPro2MsgResolver Recycle->TPro2MsgResolver
  27. //引用应为 Acquire 7次 Recycle 9次
  28. public static BytesWrapper Acquire(byte[] buffer, int offset, int size)
  29. {
  30. if (bytesWrappers.TryDequeue(out var bw))
  31. {
  32. bw.buffer = buffer;
  33. bw.offset = offset;
  34. bw.size = size;
  35. return bw;
  36. }
  37. else
  38. return new BytesWrapper(buffer, offset, size);
  39. }
  40. public static void Recycle(BytesWrapper bw)
  41. {
  42. if (bw != null && bytesWrappers.Count < MAX_BUFFER_COUNT)
  43. {
  44. bytesWrappers.Enqueue(bw);
  45. }
  46. }
  47. public static void Dispose()
  48. {
  49. while (bytesWrappers.TryDequeue(out _)) { }
  50. }
  51. }
  52. }