SequentialResult.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. namespace Caliburn.Micro.Core {
  2. using System;
  3. using System.Collections.Generic;
  4. /// <summary>
  5. /// An implementation of <see cref = "IResult" /> that enables sequential execution of multiple results.
  6. /// </summary>
  7. public class SequentialResult : IResult {
  8. readonly IEnumerator<IResult> enumerator;
  9. CoroutineExecutionContext context;
  10. /// <summary>
  11. /// Initializes a new instance of the <see cref = "SequentialResult" /> class.
  12. /// </summary>
  13. /// <param name = "enumerator">The enumerator.</param>
  14. public SequentialResult(IEnumerator<IResult> enumerator) {
  15. this.enumerator = enumerator;
  16. }
  17. /// <summary>
  18. /// Occurs when execution has completed.
  19. /// </summary>
  20. public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
  21. /// <summary>
  22. /// Executes the result using the specified context.
  23. /// </summary>
  24. /// <param name = "context">The context.</param>
  25. public void Execute(CoroutineExecutionContext context) {
  26. this.context = context;
  27. ChildCompleted(null, new ResultCompletionEventArgs());
  28. }
  29. void ChildCompleted(object sender, ResultCompletionEventArgs args) {
  30. var previous = sender as IResult;
  31. if (previous != null) {
  32. previous.Completed -= ChildCompleted;
  33. }
  34. if(args.Error != null || args.WasCancelled) {
  35. OnComplete(args.Error, args.WasCancelled);
  36. return;
  37. }
  38. var moveNextSucceeded = false;
  39. try {
  40. moveNextSucceeded = enumerator.MoveNext();
  41. }
  42. catch(Exception ex) {
  43. OnComplete(ex, false);
  44. return;
  45. }
  46. if(moveNextSucceeded) {
  47. try {
  48. var next = enumerator.Current;
  49. IoC.BuildUp(next);
  50. next.Completed += ChildCompleted;
  51. next.Execute(context);
  52. }
  53. catch(Exception ex) {
  54. OnComplete(ex, false);
  55. return;
  56. }
  57. }
  58. else {
  59. OnComplete(null, false);
  60. }
  61. }
  62. void OnComplete(Exception error, bool wasCancelled) {
  63. enumerator.Dispose();
  64. Completed(this, new ResultCompletionEventArgs { Error = error, WasCancelled = wasCancelled });
  65. }
  66. }
  67. }