AsyncLoadable.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using XGame.Framework.Asyncs;
  2. namespace XGame.Framework.Loadable
  3. {
  4. /// <summary>
  5. /// 异步加载器
  6. /// </summary>
  7. public class AsyncLoadable : ILoadAsync
  8. {
  9. public LoadState State { get; protected set; }
  10. private AsyncGroup _loadGroup;
  11. private AsyncGroup _unloadGroup;
  12. public IAsync LoadingAsync => _loadGroup;
  13. public IAsync UnloadingAsync => _unloadGroup;
  14. public IAsync LoadAsync()
  15. {
  16. Assert.IsTrue(State == LoadState.None || State == LoadState.Unloaded, $"Connot LoadAsync On State {State} Loadable: {this} ");
  17. State = LoadState.Loading;
  18. var loadGroup = new AsyncGroup();
  19. _loadGroup = loadGroup;
  20. try
  21. {
  22. OnLoadAsync(loadGroup);
  23. }
  24. catch (System.Exception e)
  25. {
  26. Log.Exception($"AsyncLoadable.OnLoadAsync Error: \n", e);
  27. }
  28. loadGroup.On(OnLoadGroupCompleted);
  29. loadGroup.End();
  30. return loadGroup;
  31. }
  32. public IAsync UnloadAsync()
  33. {
  34. Assert.IsFalse(State != LoadState.Loading && State != LoadState.Loaded, $"Connot UnloadAsync On State {State} Loadable: {this} ");
  35. if (State == LoadState.Loading)
  36. {
  37. _loadGroup?.RemoveAll();
  38. _loadGroup = null;
  39. }
  40. State = LoadState.Unloading;
  41. var unloadGroup = new AsyncGroup();
  42. _unloadGroup = unloadGroup;
  43. try
  44. {
  45. OnUnloadAsync(unloadGroup);
  46. }
  47. catch (System.Exception e)
  48. {
  49. Log.Exception($"AsyncLoadable.OnUnloadAsync Error: \n", e);
  50. }
  51. unloadGroup.On(OnUnloadGroupCompleted);
  52. unloadGroup.End();
  53. return unloadGroup;
  54. }
  55. private void OnLoadGroupCompleted(IAsync async = null)
  56. {
  57. State = LoadState.Loaded;
  58. _loadGroup = null;
  59. try
  60. {
  61. OnLoaded();
  62. }
  63. catch (System.Exception e)
  64. {
  65. Log.Exception($"AsyncLoadable.OnLoaded Error: \n", e);
  66. }
  67. }
  68. private void OnUnloadGroupCompleted(IAsync async = null)
  69. {
  70. State = LoadState.Unloaded;
  71. _unloadGroup = null;
  72. try
  73. {
  74. OnUnloaded();
  75. }
  76. catch (System.Exception e)
  77. {
  78. Log.Exception($"AsyncLoadable.OnUnloaded Error: \n", e);
  79. }
  80. }
  81. public void ClearAsyncs()
  82. {
  83. State = LoadState.None;
  84. _loadGroup?.RemoveAll();
  85. _loadGroup = null;
  86. _unloadGroup?.RemoveAll();
  87. _unloadGroup = null;
  88. }
  89. protected virtual void OnLoaded() { }
  90. protected virtual void OnUnloaded() { }
  91. protected virtual void OnLoadAsync(IAsyncGroup group) { }
  92. protected virtual void OnUnloadAsync(IAsyncGroup group) { }
  93. }
  94. }