ConcurrencyAbstractionLayer.Default.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_THREAD
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Reactive.Disposables;
  6. using System.Threading;
  7. namespace System.Reactive.Concurrency
  8. {
  9. //
  10. // WARNING: This code is kept *identically* in two places. One copy is kept in System.Reactive.Core for non-PLIB platforms.
  11. // Another copy is kept in System.Reactive.PlatformServices to enlighten the default lowest common denominator
  12. // behavior of Rx for PLIB when used on a more capable platform.
  13. //
  14. internal class DefaultConcurrencyAbstractionLayer/*Impl*/ : IConcurrencyAbstractionLayer
  15. {
  16. public IDisposable StartTimer(Action<object> action, object state, TimeSpan dueTime)
  17. {
  18. return new Timer(action, state, Normalize(dueTime));
  19. }
  20. public IDisposable StartPeriodicTimer(Action action, TimeSpan period)
  21. {
  22. //
  23. // MSDN documentation states the following:
  24. //
  25. // "If period is zero (0) or negative one (-1) milliseconds and dueTime is positive, callback is invoked once;
  26. // the periodic behavior of the timer is disabled, but can be re-enabled using the Change method."
  27. //
  28. if (period <= TimeSpan.Zero)
  29. throw new ArgumentOutOfRangeException("period");
  30. return new PeriodicTimer(action, period);
  31. }
  32. public IDisposable QueueUserWorkItem(Action<object> action, object state)
  33. {
  34. System.Threading.ThreadPool.QueueUserWorkItem(_ => action(_), state);
  35. return Disposable.Empty;
  36. }
  37. #if USE_SLEEP_MS
  38. public void Sleep(TimeSpan timeout)
  39. {
  40. System.Threading.Thread.Sleep((int)Normalize(timeout).TotalMilliseconds);
  41. }
  42. #else
  43. public void Sleep(TimeSpan timeout)
  44. {
  45. System.Threading.Thread.Sleep(Normalize(timeout));
  46. }
  47. #endif
  48. public IStopwatch StartStopwatch()
  49. {
  50. return new DefaultStopwatch();
  51. }
  52. public bool SupportsLongRunning
  53. {
  54. get { return true; }
  55. }
  56. public void StartThread(Action<object> action, object state)
  57. {
  58. new Thread(() =>
  59. {
  60. action(state);
  61. }).Start();
  62. }
  63. private static TimeSpan Normalize(TimeSpan dueTime)
  64. {
  65. if (dueTime < TimeSpan.Zero)
  66. return TimeSpan.Zero;
  67. return dueTime;
  68. }
  69. class Timer : IDisposable
  70. {
  71. //
  72. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  73. //
  74. #if !NO_HASHSET
  75. private static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  76. #else
  77. private static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  78. #endif
  79. private Action<object> _action;
  80. private System.Threading.Timer _timer;
  81. private bool _hasAdded;
  82. private bool _hasRemoved;
  83. public Timer(Action<object> action, object state, TimeSpan dueTime)
  84. {
  85. _action = action;
  86. _timer = new System.Threading.Timer(Tick, state, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  87. lock (s_timers)
  88. {
  89. if (!_hasRemoved)
  90. {
  91. #if !NO_HASHSET
  92. s_timers.Add(_timer);
  93. #else
  94. s_timers.Add(_timer, null);
  95. #endif
  96. _hasAdded = true;
  97. }
  98. }
  99. }
  100. private void Tick(object state)
  101. {
  102. try
  103. {
  104. _action(state);
  105. }
  106. finally
  107. {
  108. Dispose();
  109. }
  110. }
  111. public void Dispose()
  112. {
  113. _action = Stubs<object>.Ignore;
  114. var timer = default(System.Threading.Timer);
  115. lock (s_timers)
  116. {
  117. if (!_hasRemoved)
  118. {
  119. timer = _timer;
  120. _timer = null;
  121. if (_hasAdded && timer != null)
  122. s_timers.Remove(timer);
  123. _hasRemoved = true;
  124. }
  125. }
  126. if (timer != null)
  127. timer.Dispose();
  128. }
  129. }
  130. class PeriodicTimer : IDisposable
  131. {
  132. //
  133. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  134. //
  135. #if !NO_HASHSET
  136. private static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  137. #else
  138. private static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  139. #endif
  140. private Action _action;
  141. private System.Threading.Timer _timer;
  142. public PeriodicTimer(Action action, TimeSpan period)
  143. {
  144. _action = action;
  145. _timer = new System.Threading.Timer(Tick, null, period, period);
  146. lock (s_timers)
  147. {
  148. #if !NO_HASHSET
  149. s_timers.Add(_timer);
  150. #else
  151. s_timers.Add(_timer, null);
  152. #endif
  153. }
  154. }
  155. private void Tick(object state)
  156. {
  157. _action();
  158. }
  159. public void Dispose()
  160. {
  161. var timer = default(System.Threading.Timer);
  162. lock (s_timers)
  163. {
  164. timer = _timer;
  165. _timer = null;
  166. if (timer != null)
  167. s_timers.Remove(timer);
  168. }
  169. if (timer != null)
  170. {
  171. timer.Dispose();
  172. _action = Stubs.Nop;
  173. }
  174. }
  175. }
  176. }
  177. }
  178. #else
  179. using System;
  180. using System.Reactive.Disposables;
  181. using System.Threading.Tasks;
  182. namespace System.Reactive.Concurrency
  183. {
  184. internal class DefaultConcurrencyAbstractionLayer : IConcurrencyAbstractionLayer
  185. {
  186. public IDisposable StartTimer(Action<object> action, object state, TimeSpan dueTime)
  187. {
  188. var cancel = new CancellationDisposable();
  189. Task.Delay(dueTime, cancel.Token).ContinueWith(
  190. _ => action(state),
  191. TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion
  192. );
  193. return cancel;
  194. }
  195. public IDisposable StartPeriodicTimer(Action action, TimeSpan period)
  196. {
  197. var cancel = new CancellationDisposable();
  198. var moveNext = default(Action);
  199. moveNext = () =>
  200. {
  201. Task.Delay(period, cancel.Token).ContinueWith(
  202. _ =>
  203. {
  204. moveNext();
  205. action();
  206. },
  207. TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion
  208. );
  209. };
  210. moveNext();
  211. return cancel;
  212. }
  213. public IDisposable QueueUserWorkItem(Action<object> action, object state)
  214. {
  215. var cancel = new CancellationDisposable();
  216. Task.Factory.StartNew(action, state, cancel.Token);
  217. return cancel;
  218. }
  219. public void Sleep(TimeSpan timeout)
  220. {
  221. Task.Delay(timeout).Wait();
  222. }
  223. public IStopwatch StartStopwatch()
  224. {
  225. return new DefaultStopwatch();
  226. }
  227. public bool SupportsLongRunning
  228. {
  229. get { return true; }
  230. }
  231. public void StartThread(Action<object> action, object state)
  232. {
  233. Task.Factory.StartNew(() =>
  234. {
  235. action(state);
  236. }, TaskCreationOptions.LongRunning);
  237. }
  238. }
  239. }
  240. #endif