ConfigComponent.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. namespace ET
  5. {
  6. /// <summary>
  7. /// Config组件会扫描所有的有ConfigAttribute标签的配置,加载进来
  8. /// </summary>
  9. public class ConfigComponent: Singleton<ConfigComponent>
  10. {
  11. public struct GetAllConfigBytes
  12. {
  13. }
  14. public struct GetOneConfigBytes
  15. {
  16. public string ConfigName;
  17. }
  18. private readonly Dictionary<Type, ISingleton> allConfig = new Dictionary<Type, ISingleton>();
  19. public override void Dispose()
  20. {
  21. foreach (var kv in this.allConfig)
  22. {
  23. kv.Value.Destroy();
  24. }
  25. }
  26. public object LoadOneConfig(Type configType)
  27. {
  28. this.allConfig.TryGetValue(configType, out ISingleton oneConfig);
  29. if (oneConfig != null)
  30. {
  31. oneConfig.Destroy();
  32. }
  33. byte[] oneConfigBytes = EventSystem.Instance.Invoke<GetOneConfigBytes, byte[]>(0, new GetOneConfigBytes() {ConfigName = configType.FullName});
  34. object category = SerializeHelper.Deserialize(configType, oneConfigBytes, 0, oneConfigBytes.Length);
  35. ISingleton singleton = category as ISingleton;
  36. singleton.Register();
  37. this.allConfig[configType] = singleton;
  38. return category;
  39. }
  40. public void Load()
  41. {
  42. this.allConfig.Clear();
  43. Dictionary<Type, byte[]> configBytes = EventSystem.Instance.Invoke<GetAllConfigBytes, Dictionary<Type, byte[]>>(0, new GetAllConfigBytes());
  44. foreach (Type type in configBytes.Keys)
  45. {
  46. byte[] oneConfigBytes = configBytes[type];
  47. this.LoadOneInThread(type, oneConfigBytes);
  48. }
  49. }
  50. public async ETTask LoadAsync()
  51. {
  52. this.allConfig.Clear();
  53. Dictionary<Type, byte[]> configBytes = EventSystem.Instance.Invoke<GetAllConfigBytes, Dictionary<Type, byte[]>>(0, new GetAllConfigBytes());
  54. using ListComponent<Task> listTasks = ListComponent<Task>.Create();
  55. foreach (Type type in configBytes.Keys)
  56. {
  57. byte[] oneConfigBytes = configBytes[type];
  58. Task task = Task.Run(() => LoadOneInThread(type, oneConfigBytes));
  59. listTasks.Add(task);
  60. }
  61. await Task.WhenAll(listTasks.ToArray());
  62. foreach (ISingleton category in this.allConfig.Values)
  63. {
  64. category.Register();
  65. }
  66. Log.Debug("register all config ok");
  67. }
  68. private void LoadOneInThread(Type configType, byte[] oneConfigBytes)
  69. {
  70. object category = SerializeHelper.Deserialize(configType, oneConfigBytes, 0, oneConfigBytes.Length);
  71. Log.Debug($"Deserialize: {configType} ok");
  72. lock (this)
  73. {
  74. this.allConfig[configType] = category as ISingleton;
  75. }
  76. }
  77. }
  78. }