ThreadPoolScheduler.Windows.cs 7.5 KB

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