SchedulerOperation.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if HAS_AWAIT
  3. using System.ComponentModel;
  4. using System.Runtime.CompilerServices;
  5. using System.Threading;
  6. namespace System.Reactive.Concurrency
  7. {
  8. /// <summary>
  9. /// Represents an awaitable scheduler operation. Awaiting the object causes the continuation to be posted back to the originating scheduler's work queue.
  10. /// </summary>
  11. public sealed class SchedulerOperation
  12. {
  13. private readonly Func<Action, IDisposable> _schedule;
  14. private readonly CancellationToken _cancellationToken;
  15. private readonly bool _postBackToOriginalContext;
  16. internal SchedulerOperation(Func<Action, IDisposable> schedule, CancellationToken cancellationToken)
  17. : this(schedule, cancellationToken, false)
  18. {
  19. }
  20. internal SchedulerOperation(Func<Action, IDisposable> schedule, CancellationToken cancellationToken, bool postBackToOriginalContext)
  21. {
  22. _schedule = schedule;
  23. _cancellationToken = cancellationToken;
  24. _postBackToOriginalContext = postBackToOriginalContext;
  25. }
  26. /// <summary>
  27. /// Controls whether the continuation is run on the originating synchronization context (false by default).
  28. /// </summary>
  29. /// <param name="continueOnCapturedContext">true to run the continuation on the captured synchronization context; false otherwise (default).</param>
  30. /// <returns>Scheduler operation object with configured await behavior.</returns>
  31. public SchedulerOperation ConfigureAwait(bool continueOnCapturedContext)
  32. {
  33. return new SchedulerOperation(_schedule, _cancellationToken, continueOnCapturedContext);
  34. }
  35. /// <summary>
  36. /// Gets an awaiter for the scheduler operation, used to post back the continuation.
  37. /// </summary>
  38. /// <returns>Awaiter for the scheduler operation.</returns>
  39. public SchedulerOperationAwaiter GetAwaiter()
  40. {
  41. return new SchedulerOperationAwaiter(_schedule, _cancellationToken, _postBackToOriginalContext);
  42. }
  43. }
  44. /// <summary>
  45. /// (Infrastructure) Scheduler operation awaiter type used by the code generated for C# await and Visual Basic Await expressions.
  46. /// </summary>
  47. [EditorBrowsable(EditorBrowsableState.Never)]
  48. public sealed class SchedulerOperationAwaiter
  49. : INotifyCompletion
  50. {
  51. private readonly Func<Action, IDisposable> _schedule;
  52. private readonly CancellationToken _cancellationToken;
  53. private readonly bool _postBackToOriginalContext;
  54. private readonly CancellationTokenRegistration _ctr;
  55. internal SchedulerOperationAwaiter(Func<Action, IDisposable> schedule, CancellationToken cancellationToken, bool postBackToOriginalContext)
  56. {
  57. _schedule = schedule;
  58. _cancellationToken = cancellationToken;
  59. _postBackToOriginalContext = postBackToOriginalContext;
  60. if (cancellationToken.CanBeCanceled)
  61. {
  62. _ctr = _cancellationToken.Register(Cancel);
  63. }
  64. }
  65. /// <summary>
  66. /// Indicates whether the scheduler operation has completed. Returns false unless cancellation was already requested.
  67. /// </summary>
  68. public bool IsCompleted
  69. {
  70. get { return _cancellationToken.IsCancellationRequested; }
  71. }
  72. /// <summary>
  73. /// Completes the scheduler operation, throwing an OperationCanceledException in case cancellation was requested.
  74. /// </summary>
  75. public void GetResult()
  76. {
  77. _cancellationToken.ThrowIfCancellationRequested();
  78. }
  79. /// <summary>
  80. /// Registers the continuation with the scheduler operation.
  81. /// </summary>
  82. /// <param name="continuation">Continuation to be run on the originating scheduler.</param>
  83. public void OnCompleted(Action continuation)
  84. {
  85. if (continuation == null)
  86. throw new ArgumentNullException("continuation");
  87. if (_continuation != null)
  88. throw new InvalidOperationException(Strings_Core.SCHEDULER_OPERATION_ALREADY_AWAITED);
  89. if (_postBackToOriginalContext)
  90. {
  91. var ctx = SynchronizationContext.Current;
  92. if (ctx != null)
  93. {
  94. var original = continuation;
  95. continuation = () =>
  96. {
  97. //
  98. // No need for OperationStarted and OperationCompleted calls here;
  99. // this code is invoked through await support and will have a way
  100. // to observe its start/complete behavior, either through returned
  101. // Task objects or the async method builder's interaction with the
  102. // SynchronizationContext object.
  103. //
  104. // In general though, Rx doesn't play nicely with synchronization
  105. // contexts objects at the scheduler level. It's possible to start
  106. // async operations by calling Schedule, without a way to observe
  107. // their completion. Not interacting with SynchronizationContext
  108. // is a concious design decision as the performance impact was non
  109. // negligable and our schedulers abstract over more constructs.
  110. //
  111. ctx.Post(a => ((Action)a)(), original);
  112. };
  113. }
  114. }
  115. var ran = 0;
  116. _continuation = () =>
  117. {
  118. if (Interlocked.Exchange(ref ran, 1) == 0)
  119. {
  120. _ctr.Dispose(); // no null-check needed (struct)
  121. continuation();
  122. }
  123. };
  124. _work = _schedule(_continuation);
  125. }
  126. private volatile Action _continuation;
  127. private volatile IDisposable _work;
  128. private void Cancel()
  129. {
  130. var w = _work;
  131. if (w != null)
  132. w.Dispose();
  133. var c = _continuation;
  134. if (c != null)
  135. c();
  136. }
  137. }
  138. }
  139. #endif