AsyncHelper.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Reflection;
  3. using System.Threading.Tasks;
  4. using Nito.AsyncEx;
  5. namespace Abp.Threading
  6. {
  7. /// <summary>
  8. /// Provides some helper methods to work with async methods.
  9. /// </summary>
  10. public static class AsyncHelper
  11. {
  12. /// <summary>
  13. /// Checks if given method is an async method.
  14. /// </summary>
  15. /// <param name="method">A method to check</param>
  16. public static bool IsAsync(this MethodInfo method)
  17. {
  18. return (
  19. method.ReturnType == typeof(Task) ||
  20. (method.ReturnType.GetTypeInfo().IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
  21. );
  22. }
  23. /// <summary>
  24. /// Checks if given method is an async method.
  25. /// </summary>
  26. /// <param name="method">A method to check</param>
  27. [Obsolete("Use MethodInfo.IsAsync() extension method!")]
  28. public static bool IsAsyncMethod(MethodInfo method)
  29. {
  30. return method.IsAsync();
  31. }
  32. /// <summary>
  33. /// Runs a async method synchronously.
  34. /// </summary>
  35. /// <param name="func">A function that returns a result</param>
  36. /// <typeparam name="TResult">Result type</typeparam>
  37. /// <returns>Result of the async operation</returns>
  38. public static TResult RunSync<TResult>(Func<Task<TResult>> func)
  39. {
  40. return AsyncContext.Run(func);
  41. }
  42. /// <summary>
  43. /// Runs a async method synchronously.
  44. /// </summary>
  45. /// <param name="action">An async action</param>
  46. public static void RunSync(Func<Task> action)
  47. {
  48. AsyncContext.Run(action);
  49. }
  50. }
  51. }