DelegateResult.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. namespace Caliburn.Micro.Core {
  2. using System;
  3. /// <summary>
  4. /// A result that executes an <see cref="System.Action"/>.
  5. /// </summary>
  6. public class DelegateResult : IResult {
  7. readonly Action toExecute;
  8. /// <summary>
  9. /// Initializes a new instance of the <see cref="DelegateResult"/> class.
  10. /// </summary>
  11. /// <param name="action">The action.</param>
  12. public DelegateResult(Action action) {
  13. toExecute = action;
  14. }
  15. /// <summary>
  16. /// Executes the result using the specified context.
  17. /// </summary>
  18. /// <param name="context">The context.</param>
  19. public void Execute(CoroutineExecutionContext context) {
  20. var eventArgs = new ResultCompletionEventArgs();
  21. try {
  22. toExecute();
  23. }
  24. catch (Exception ex) {
  25. eventArgs.Error = ex;
  26. }
  27. Completed(this, eventArgs);
  28. }
  29. /// <summary>
  30. /// Occurs when execution has completed.
  31. /// </summary>
  32. public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
  33. }
  34. /// <summary>
  35. /// A result that executes a <see cref="System.Func&lt;TResult&gt;"/>
  36. /// </summary>
  37. /// <typeparam name="TResult">The type of the result.</typeparam>
  38. public class DelegateResult<TResult> : IResult<TResult> {
  39. readonly Func<TResult> toExecute;
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="DelegateResult&lt;TResult&gt;"/> class.
  42. /// </summary>
  43. /// <param name="action">The action.</param>
  44. public DelegateResult(Func<TResult> action) {
  45. toExecute = action;
  46. }
  47. /// <summary>
  48. /// Executes the result using the specified context.
  49. /// </summary>
  50. /// <param name="context">The context.</param>
  51. public void Execute(CoroutineExecutionContext context) {
  52. var eventArgs = new ResultCompletionEventArgs();
  53. try {
  54. Result = toExecute();
  55. }
  56. catch (Exception ex) {
  57. eventArgs.Error = ex;
  58. }
  59. Completed(this, eventArgs);
  60. }
  61. /// <summary>
  62. /// Gets the result.
  63. /// </summary>
  64. public TResult Result { get; private set; }
  65. /// <summary>
  66. /// Occurs when execution has completed.
  67. /// </summary>
  68. public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
  69. }
  70. }