AsyncEx.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. namespace XGame.Framework.Asyncs
  3. {
  4. /// <summary>
  5. /// 异步扩展方法类!
  6. /// </summary>
  7. public static class AsyncEx
  8. {
  9. /// <summary>
  10. /// 将Async加入到AsyncGroup 方便写代码!放心使用不用担心空指针
  11. /// </summary>
  12. /// <param name="async"></param>
  13. /// <param name="group"></param>
  14. /// <returns></returns>
  15. public static T Join<T>(this T async, IAsyncGroup group) where T : IAsync
  16. {
  17. if (async != null && group != null)
  18. {
  19. group.AddAsync(async);
  20. }
  21. return async;
  22. }
  23. /// <summary>
  24. /// 执行成功且没有发生任何异常
  25. /// </summary>
  26. /// <typeparam name="TAsync"></typeparam>
  27. /// <param name="async"></param>
  28. /// <param name="action"></param>
  29. /// <returns></returns>
  30. public static IAsync Then(this IAsync async, Action<IAsync> action)
  31. {
  32. if (action == null) return async;
  33. if (async == null || async.IsCompleted)
  34. {
  35. action.Invoke(async);
  36. return async;
  37. }
  38. async.On(a =>
  39. {
  40. if (a.Exception == null)
  41. {
  42. action.Invoke(async);
  43. }
  44. });
  45. return async;
  46. }
  47. /// <summary>
  48. /// 异步过程中产生了所关注的异常
  49. /// 如果关注所有异常TException 设置为 Exception
  50. /// </summary>
  51. /// <typeparam name="TAsync"></typeparam>
  52. /// <typeparam name="TException"></typeparam>
  53. /// <param name="async"></param>
  54. /// <param name="action"></param>
  55. /// <returns></returns>
  56. public static TAsync Catch<TAsync, TException>(this TAsync async, Action<TException> action) where TAsync : IAsync where TException : Exception
  57. {
  58. if (async == null || action == null) return async;
  59. async.On(a =>
  60. {
  61. TException exc = a.Exception as TException;
  62. if (exc != null)
  63. {
  64. action.Invoke(exc);
  65. }
  66. });
  67. return async;
  68. }
  69. public static void SaveInvoke(this OnAsyncCompleted onAsyncCompleted, IAsync aAsync)
  70. {
  71. try
  72. {
  73. onAsyncCompleted?.Invoke(aAsync);
  74. }
  75. catch (Exception ex)
  76. {
  77. Log.Exception($"【Async Exception】Method:{onAsyncCompleted?.Method.Name ?? "null"} Async:{aAsync?.ToString() ?? "null"}\n", ex);
  78. }
  79. }
  80. public static void SaveInvoke(this IAsyncListener listener, IAsync aAsync)
  81. {
  82. try
  83. {
  84. listener?.OnAsyncCompleted(aAsync);
  85. }
  86. catch (Exception ex)
  87. {
  88. Log.Exception($"【Async Exception】Listener:{listener?.GetType().FullName ?? "null"} Async:{aAsync?.ToString() ?? "null"}\n ", ex);
  89. }
  90. }
  91. }
  92. }