MessagePool.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ETHotfix
  4. {
  5. // 客户端为了0GC需要消息池,服务端消息需要跨协程不需要消息池
  6. public class MessagePool
  7. {
  8. public static MessagePool Instance { get; } = new MessagePool();
  9. #if !SERVER
  10. private readonly Dictionary<Type, Queue<object>> dictionary = new Dictionary<Type, Queue<object>>();
  11. #endif
  12. public object Fetch(Type type)
  13. {
  14. #if !SERVER
  15. Queue<object> queue;
  16. if (!this.dictionary.TryGetValue(type, out queue))
  17. {
  18. queue = new Queue<object>();
  19. this.dictionary.Add(type, queue);
  20. }
  21. object obj;
  22. if (queue.Count > 0)
  23. {
  24. obj = queue.Dequeue();
  25. }
  26. else
  27. {
  28. obj = Activator.CreateInstance(type);
  29. }
  30. return obj;
  31. #else
  32. return Activator.CreateInstance(type);
  33. #endif
  34. }
  35. public T Fetch<T>() where T: class
  36. {
  37. T t = (T) this.Fetch(typeof(T));
  38. return t;
  39. }
  40. public void Recycle(object obj)
  41. {
  42. #if !SERVER
  43. Type type = obj.GetType();
  44. Queue<object> queue;
  45. if (!this.dictionary.TryGetValue(type, out queue))
  46. {
  47. queue = new Queue<object>();
  48. this.dictionary.Add(type, queue);
  49. }
  50. queue.Enqueue(obj);
  51. #endif
  52. }
  53. }
  54. }