MessagePool.cs 1.2 KB

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