MemoryMonitor.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace XGame.Framework.Memory
  4. {
  5. public delegate void CleanMemoryDelegate();
  6. /// <summary>
  7. /// 内存监控,业务不要用
  8. /// </summary>
  9. public static class MemoryMonitor
  10. {
  11. private static HashSet<CleanMemoryDelegate> _delegateRegisters = new HashSet<CleanMemoryDelegate>();
  12. static MemoryMonitor()
  13. {
  14. Application.lowMemory += OnLowMemory;
  15. }
  16. private static void OnLowMemory()
  17. {
  18. Log.Info("内存警告!!");
  19. CleanMemory();
  20. }
  21. public static void CleanMemory()
  22. {
  23. Log.Info("Clean Memory!!");
  24. foreach (var register in _delegateRegisters)
  25. {
  26. try
  27. {
  28. register?.Invoke();
  29. }
  30. catch (System.Exception e)
  31. {
  32. Log.Error($"Memory Warning Delegate Exception: Message: {e.Message}, StackTrace: {e.StackTrace}");
  33. }
  34. }
  35. //TODO
  36. //AssetHelper.UnloadUnusedAssets();
  37. System.GC.Collect();
  38. Log.Info("Clean Memory Done...");
  39. }
  40. public static void Register(CleanMemoryDelegate register)
  41. {
  42. if (register == null)
  43. return;
  44. if (!_delegateRegisters.Contains(register))
  45. _delegateRegisters.Add(register);
  46. }
  47. public static void UnRegister(CleanMemoryDelegate unRegister)
  48. {
  49. if (unRegister == null)
  50. return;
  51. if (_delegateRegisters.Contains(unRegister))
  52. _delegateRegisters.Remove(unRegister);
  53. }
  54. internal static void Dispose()
  55. {
  56. _delegateRegisters.Clear();
  57. }
  58. }
  59. }