Timer.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //
  2. // System.Threading.Timer.cs
  3. //
  4. // Authors:
  5. // Dick Porter ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. //
  8. // (C) 2001, 2002 Ximian, Inc. http://www.ximian.com
  9. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Runtime.InteropServices;
  31. using System.Collections;
  32. namespace System.Threading
  33. {
  34. #if NET_2_0
  35. [ComVisible (true)]
  36. #endif
  37. public sealed class Timer : MarshalByRefObject, IDisposable
  38. {
  39. #region Timer instance fields
  40. TimerCallback callback;
  41. object state;
  42. long due_time_ms;
  43. long period_ms;
  44. long next_run; // in ticks
  45. bool disposed;
  46. #endregion
  47. // timers that expire after FutureTime will be put in future_jobs
  48. // 5 seconds seems reasonable, this must be at least 1 second
  49. const long FutureTime = 5 * 1000;
  50. const long FutureTimeTicks = FutureTime * TimeSpan.TicksPerMillisecond;
  51. #region Timer static fields
  52. static Thread scheduler;
  53. static Hashtable jobs;
  54. static Hashtable future_jobs;
  55. static Timer future_checker;
  56. static AutoResetEvent change_event;
  57. static object locker;
  58. #endregion
  59. /* we use a static initializer to avoid race issues with the thread creation */
  60. static Timer ()
  61. {
  62. change_event = new AutoResetEvent (false);
  63. jobs = new Hashtable ();
  64. future_jobs = new Hashtable ();
  65. locker = new object ();
  66. scheduler = new Thread (SchedulerThread);
  67. scheduler.IsBackground = true;
  68. scheduler.Start ();
  69. }
  70. static long Ticks ()
  71. {
  72. return DateTime.GetTimeMonotonic ();
  73. }
  74. static private void SchedulerThread ()
  75. {
  76. Thread.CurrentThread.Name = "Timer-Scheduler";
  77. while (true) {
  78. long min_next_run = long.MaxValue;
  79. lock (locker) {
  80. ArrayList expired = null;
  81. long ticks = Ticks ();
  82. bool future_queue_activated = false;
  83. foreach (Timer t1 in jobs.Keys) {
  84. if (t1.next_run <= ticks) {
  85. ThreadPool.QueueUserWorkItem (new WaitCallback (t1.callback), t1.state);
  86. if (t1.period_ms == -1 || ((t1.period_ms == 0 | t1.period_ms == Timeout.Infinite) && t1.due_time_ms != Timeout.Infinite)) {
  87. t1.next_run = long.MaxValue;
  88. if (expired == null)
  89. expired = new ArrayList ();
  90. expired.Add (t1);
  91. } else {
  92. t1.next_run = Ticks () + TimeSpan.TicksPerMillisecond * t1.period_ms;
  93. // if it expires too late, postpone to future_jobs
  94. if (t1.period_ms >= FutureTime) {
  95. if (future_jobs.Count == 0)
  96. future_queue_activated = true;
  97. future_jobs [t1] = t1;
  98. if (expired == null)
  99. expired = new ArrayList ();
  100. expired.Add (t1);
  101. }
  102. }
  103. }
  104. if (t1.next_run != long.MaxValue) {
  105. min_next_run = Math.Min (min_next_run, t1.next_run);
  106. }
  107. }
  108. if (future_queue_activated) {
  109. StartFutureHandler ();
  110. min_next_run = Math.Min (min_next_run, future_checker.next_run);
  111. }
  112. if (expired != null) {
  113. int count = expired.Count;
  114. for (int i = 0; i < count; ++i) {
  115. jobs.Remove (expired [i]);
  116. }
  117. expired.Clear ();
  118. if (count > 50)
  119. expired = null;
  120. }
  121. }
  122. if (min_next_run != long.MaxValue) {
  123. long diff = min_next_run - Ticks ();
  124. if (diff >= 0)
  125. change_event.WaitOne ((int)(diff / TimeSpan.TicksPerMillisecond), true);
  126. } else {
  127. change_event.WaitOne (Timeout.Infinite, true);
  128. }
  129. }
  130. }
  131. public Timer (TimerCallback callback, object state, int dueTime, int period)
  132. {
  133. if (dueTime < -1)
  134. throw new ArgumentOutOfRangeException ("dueTime");
  135. if (period < -1)
  136. throw new ArgumentOutOfRangeException ("period");
  137. Init (callback, state, dueTime, period);
  138. }
  139. public Timer (TimerCallback callback, object state, long dueTime, long period)
  140. {
  141. if (dueTime < -1)
  142. throw new ArgumentOutOfRangeException ("dueTime");
  143. if (period < -1)
  144. throw new ArgumentOutOfRangeException ("period");
  145. Init (callback, state, dueTime, period);
  146. }
  147. public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
  148. : this (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds)
  149. {
  150. }
  151. [CLSCompliant(false)]
  152. public Timer (TimerCallback callback, object state, uint dueTime, uint period)
  153. : this (callback, state, (long) dueTime, (long) period)
  154. {
  155. }
  156. #if NET_2_0
  157. public Timer (TimerCallback callback)
  158. {
  159. Init (callback, this, Timeout.Infinite, Timeout.Infinite);
  160. }
  161. #endif
  162. void Init (TimerCallback callback, object state, long dueTime, long period)
  163. {
  164. if (callback == null)
  165. throw new ArgumentNullException ("callback");
  166. this.callback = callback;
  167. this.state = state;
  168. Change (dueTime, period);
  169. }
  170. public bool Change (int dueTime, int period)
  171. {
  172. return Change ((long)dueTime, (long)period);
  173. }
  174. // FIXME: handle this inside the scheduler, so no additional timer is ever active
  175. static void CheckFuture (object state) {
  176. lock (locker) {
  177. ArrayList moved = null;
  178. long now = Ticks ();
  179. foreach (Timer t1 in future_jobs.Keys) {
  180. if (t1.next_run <= now + FutureTimeTicks) {
  181. if (moved == null)
  182. moved = new ArrayList ();
  183. moved.Add (t1);
  184. jobs [t1] = t1;
  185. }
  186. }
  187. if (moved != null) {
  188. int count = moved.Count;
  189. for (int i = 0; i < count; ++i) {
  190. future_jobs.Remove (moved [i]);
  191. }
  192. moved.Clear ();
  193. change_event.Set ();
  194. }
  195. // no point in keeping this helper timer running
  196. if (future_jobs.Count == 0) {
  197. future_checker.Dispose ();
  198. future_checker = null;
  199. }
  200. }
  201. }
  202. static void StartFutureHandler ()
  203. {
  204. if (future_checker == null)
  205. future_checker = new Timer (CheckFuture, null, FutureTime - 500, FutureTime - 500);
  206. }
  207. public bool Change (long dueTime, long period)
  208. {
  209. if(dueTime > 4294967294)
  210. throw new NotSupportedException ("Due time too large");
  211. if(period > 4294967294)
  212. throw new NotSupportedException ("Period too large");
  213. if (dueTime < -1)
  214. throw new ArgumentOutOfRangeException ("dueTime");
  215. if (period < -1)
  216. throw new ArgumentOutOfRangeException ("period");
  217. if (disposed)
  218. return false;
  219. due_time_ms = dueTime;
  220. period_ms = period;
  221. long now = Ticks ();
  222. if (dueTime == 0) {
  223. next_run = now;
  224. } else if (dueTime == Timeout.Infinite) {
  225. next_run = long.MaxValue;
  226. } else {
  227. next_run = dueTime * TimeSpan.TicksPerMillisecond + now;
  228. }
  229. lock (locker) {
  230. if (next_run != long.MaxValue) {
  231. bool is_future = next_run - now > FutureTimeTicks;
  232. Timer t = jobs [this] as Timer;
  233. if (t == null) {
  234. t = future_jobs [this] as Timer;
  235. } else {
  236. if (is_future) {
  237. future_jobs [this] = this;
  238. jobs.Remove (this);
  239. }
  240. }
  241. if (t == null) {
  242. if (is_future)
  243. future_jobs [this] = this;
  244. else
  245. jobs [this] = this;
  246. }
  247. if (is_future)
  248. StartFutureHandler ();
  249. change_event.Set ();
  250. } else {
  251. jobs.Remove (this);
  252. future_jobs.Remove (this);
  253. }
  254. }
  255. return true;
  256. }
  257. public bool Change (TimeSpan dueTime, TimeSpan period)
  258. {
  259. return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
  260. }
  261. [CLSCompliant(false)]
  262. public bool Change (uint dueTime, uint period)
  263. {
  264. if (dueTime > Int32.MaxValue)
  265. throw new NotSupportedException ("Due time too large");
  266. if (period > Int32.MaxValue)
  267. throw new NotSupportedException ("Period too large");
  268. return Change ((long) dueTime, (long) period);
  269. }
  270. public void Dispose ()
  271. {
  272. disposed = true;
  273. lock (locker) {
  274. jobs.Remove (this);
  275. future_jobs.Remove (this);
  276. }
  277. }
  278. public bool Dispose (WaitHandle notifyObject)
  279. {
  280. Dispose ();
  281. NativeEventCalls.SetEvent_internal (notifyObject.Handle);
  282. return true;
  283. }
  284. }
  285. }