MessagePool.cs 1.5 KB

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