Guest User

Untitled

a guest
Jan 24th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. namespace AsyncTests.Infrastructure.Commands
  2. {
  3. #region using
  4.  
  5. using System;
  6. using System.Threading.Tasks;
  7.  
  8. using log4net;
  9.  
  10. #endregion
  11.  
  12. /// <summary>
  13. /// Async command execution.
  14. /// </summary>
  15. public static class AsyncCommandExecutor<T>
  16. {
  17. // NOTE: don't care about sharing this between instances.
  18. // ReSharper disable StaticFieldInGenericType
  19. private static readonly ILog Log = LogManager.GetLogger(typeof(AsyncCommandExecutor<>));
  20. // ReSharper restore StaticFieldInGenericType
  21.  
  22. /// <summary>
  23. /// Executes the supplied command asynchronously.
  24. /// </summary>
  25. /// <param name="command">The command to execute.</param>
  26. public static async Task<T> Execute(IAsyncCommand<T> command, Action success = null, Action error = null)
  27. {
  28.  
  29. var task = Task.Factory.StartNew(
  30. () =>
  31. {
  32. return command.Execute();
  33. });
  34. task.ContinueWith(
  35. t =>
  36. Log.Error(string.Format("'{0}' failed, something terrible happened.", command.GetType()), t.Exception),
  37. TaskContinuationOptions.OnlyOnFaulted);
  38.  
  39. T result = await task;
  40.  
  41. if (success != null && command.Successful)
  42. {
  43. success();
  44. }
  45. if (error != null && !command.Successful)
  46. {
  47. error();
  48. }
  49.  
  50. return result;
  51. }
  52. }
  53. }
Add Comment
Please, Sign In to add comment