1
0

ThreadPoolScheduler.Windows.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if WINDOWS
  3. using System.Reactive.Concurrency;
  4. using System.Reactive.Disposables;
  5. using Windows.System.Threading;
  6. namespace System.Reactive.Concurrency
  7. {
  8. /// <summary>
  9. /// Represents an object that schedules units of work on the Windows Runtime thread pool.
  10. /// </summary>
  11. /// <seealso cref="ThreadPoolScheduler.Default">Singleton instance of this type exposed through this static property.</seealso>
  12. [CLSCompliant(false)]
  13. public sealed class ThreadPoolScheduler : LocalScheduler, ISchedulerPeriodic
  14. {
  15. private readonly WorkItemPriority _priority;
  16. private readonly WorkItemOptions _options;
  17. private static Lazy<ThreadPoolScheduler> s_default = new Lazy<ThreadPoolScheduler>(() => new ThreadPoolScheduler());
  18. /// <summary>
  19. /// Constructs a ThreadPoolScheduler that schedules units of work on the Windows ThreadPool.
  20. /// </summary>
  21. public ThreadPoolScheduler()
  22. {
  23. }
  24. /// <summary>
  25. /// Constructs a ThreadPoolScheduler that schedules units of work on the Windows ThreadPool with the given priority.
  26. /// </summary>
  27. /// <param name="priority">Priority for scheduled units of work.</param>
  28. public ThreadPoolScheduler(WorkItemPriority priority)
  29. {
  30. _priority = priority;
  31. _options = WorkItemOptions.None;
  32. }
  33. /// <summary>
  34. /// Constructs a ThreadPoolScheduler that schedules units of work on the Windows ThreadPool with the given priority.
  35. /// </summary>
  36. /// <param name="priority">Priority for scheduled units of work.</param>
  37. /// <param name="options">Options that configure how work is scheduled.</param>
  38. public ThreadPoolScheduler(WorkItemPriority priority, WorkItemOptions options)
  39. {
  40. _priority = priority;
  41. _options = options;
  42. }
  43. /// <summary>
  44. /// Gets the singleton instance of the Windows Runtime thread pool scheduler.
  45. /// </summary>
  46. public static ThreadPoolScheduler Default
  47. {
  48. get
  49. {
  50. return s_default.Value;
  51. }
  52. }
  53. /// <summary>
  54. /// Gets the priority at which work is scheduled.
  55. /// </summary>
  56. public WorkItemPriority Priority
  57. {
  58. get { return _priority; }
  59. }
  60. /// <summary>
  61. /// Gets the options that configure how work is scheduled.
  62. /// </summary>
  63. public WorkItemOptions Options
  64. {
  65. get { return _options; }
  66. }
  67. /// <summary>
  68. /// Schedules an action to be executed.
  69. /// </summary>
  70. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  71. /// <param name="state">State passed to the action to be executed.</param>
  72. /// <param name="action">Action to be executed.</param>
  73. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  74. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  75. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  76. {
  77. if (action == null)
  78. throw new ArgumentNullException("action");
  79. var d = new SingleAssignmentDisposable();
  80. var res = global::Windows.System.Threading.ThreadPool.RunAsync(iaa =>
  81. {
  82. if (!d.IsDisposed)
  83. d.Disposable = action(this, state);
  84. }, _priority, _options);
  85. return new CompositeDisposable(
  86. d,
  87. Disposable.Create(res.Cancel)
  88. );
  89. }
  90. /// <summary>
  91. /// Schedules an action to be executed after dueTime, using a Windows.System.Threading.ThreadPoolTimer object.
  92. /// </summary>
  93. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  94. /// <param name="state">State passed to the action to be executed.</param>
  95. /// <param name="action">Action to be executed.</param>
  96. /// <param name="dueTime">Relative time after which to execute the action.</param>
  97. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  98. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  99. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  100. {
  101. if (action == null)
  102. throw new ArgumentNullException("action");
  103. var dt = Scheduler.Normalize(dueTime);
  104. if (dt.Ticks == 0)
  105. return Schedule(state, action);
  106. var d = new SingleAssignmentDisposable();
  107. var res = global::Windows.System.Threading.ThreadPoolTimer.CreateTimer(
  108. tpt =>
  109. {
  110. if (!d.IsDisposed)
  111. d.Disposable = action(this, state);
  112. },
  113. dt
  114. );
  115. return new CompositeDisposable(
  116. d,
  117. Disposable.Create(res.Cancel)
  118. );
  119. }
  120. /// <summary>
  121. /// Schedules a periodic piece of work, using a Windows.System.Threading.ThreadPoolTimer object.
  122. /// </summary>
  123. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  124. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  125. /// <param name="period">Period for running the work periodically.</param>
  126. /// <param name="action">Action to be executed, potentially updating the state.</param>
  127. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  128. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  129. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than one millisecond.</exception>
  130. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  131. {
  132. //
  133. // The WinRT thread pool is based on the Win32 thread pool and cannot handle
  134. // sub-1ms resolution. When passing a lower period, we get single-shot
  135. // timer behavior instead. See MSDN documentation for CreatePeriodicTimer
  136. // for more information.
  137. //
  138. if (period < TimeSpan.FromMilliseconds(1))
  139. throw new ArgumentOutOfRangeException("period", Strings_PlatformServices.WINRT_NO_SUB1MS_TIMERS);
  140. if (action == null)
  141. throw new ArgumentNullException("action");
  142. var state1 = state;
  143. var gate = new AsyncLock();
  144. var res = global::Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(
  145. tpt =>
  146. {
  147. gate.Wait(() =>
  148. {
  149. state1 = action(state1);
  150. });
  151. },
  152. period
  153. );
  154. return Disposable.Create(() =>
  155. {
  156. res.Cancel();
  157. gate.Dispose();
  158. action = Stubs<TState>.I;
  159. });
  160. }
  161. }
  162. }
  163. #endif