Timer.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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-2009 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. [ComVisible (true)]
  35. public sealed class Timer : MarshalByRefObject, IDisposable
  36. {
  37. static Scheduler scheduler = Scheduler.Instance;
  38. #region Timer instance fields
  39. TimerCallback callback;
  40. object state;
  41. long due_time_ms;
  42. long period_ms;
  43. long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
  44. bool disposed;
  45. #endregion
  46. public Timer (TimerCallback callback, object state, int dueTime, int period)
  47. {
  48. Init (callback, state, dueTime, period);
  49. }
  50. public Timer (TimerCallback callback, object state, long dueTime, long period)
  51. {
  52. Init (callback, state, dueTime, period);
  53. }
  54. public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
  55. {
  56. Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
  57. }
  58. [CLSCompliant(false)]
  59. public Timer (TimerCallback callback, object state, uint dueTime, uint period)
  60. {
  61. // convert all values to long - with a special case for -1 / 0xffffffff
  62. long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
  63. long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
  64. Init (callback, state, d, p);
  65. }
  66. public Timer (TimerCallback callback)
  67. {
  68. Init (callback, this, Timeout.Infinite, Timeout.Infinite);
  69. }
  70. void Init (TimerCallback callback, object state, long dueTime, long period)
  71. {
  72. if (callback == null)
  73. throw new ArgumentNullException ("callback");
  74. this.callback = callback;
  75. this.state = state;
  76. Change (dueTime, period, true);
  77. }
  78. public bool Change (int dueTime, int period)
  79. {
  80. return Change (dueTime, period, false);
  81. }
  82. public bool Change (TimeSpan dueTime, TimeSpan period)
  83. {
  84. return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
  85. }
  86. [CLSCompliant(false)]
  87. public bool Change (uint dueTime, uint period)
  88. {
  89. // convert all values to long - with a special case for -1 / 0xffffffff
  90. long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
  91. long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
  92. return Change (d, p, false);
  93. }
  94. public void Dispose ()
  95. {
  96. if (disposed)
  97. return;
  98. disposed = true;
  99. scheduler.Remove (this);
  100. }
  101. public bool Change (long dueTime, long period)
  102. {
  103. return Change (dueTime, period, false);
  104. }
  105. const long MaxValue = UInt32.MaxValue - 1;
  106. bool Change (long dueTime, long period, bool first)
  107. {
  108. if (dueTime > MaxValue)
  109. throw new ArgumentOutOfRangeException ("Due time too large");
  110. if (period > MaxValue)
  111. throw new ArgumentOutOfRangeException ("Period too large");
  112. // Timeout.Infinite == -1, so this accept everything greater than -1
  113. if (dueTime < Timeout.Infinite)
  114. throw new ArgumentOutOfRangeException ("dueTime");
  115. if (period < Timeout.Infinite)
  116. throw new ArgumentOutOfRangeException ("period");
  117. if (disposed)
  118. return false;
  119. due_time_ms = dueTime;
  120. period_ms = period;
  121. long nr;
  122. if (dueTime == 0) {
  123. nr = 0; // Due now
  124. } else if (dueTime < 0) { // Infinite == -1
  125. nr = long.MaxValue;
  126. /* No need to call Change () */
  127. if (first) {
  128. next_run = nr;
  129. return true;
  130. }
  131. } else {
  132. nr = dueTime * TimeSpan.TicksPerMillisecond + DateTime.GetTimeMonotonic ();
  133. }
  134. scheduler.Change (this, nr);
  135. return true;
  136. }
  137. public bool Dispose (WaitHandle notifyObject)
  138. {
  139. if (notifyObject == null)
  140. throw new ArgumentNullException ("notifyObject");
  141. Dispose ();
  142. NativeEventCalls.SetEvent_internal (notifyObject.Handle);
  143. return true;
  144. }
  145. sealed class TimerComparer : IComparer {
  146. public int Compare (object x, object y)
  147. {
  148. Timer tx = (x as Timer);
  149. if (tx == null)
  150. return -1;
  151. Timer ty = (y as Timer);
  152. if (ty == null)
  153. return 1;
  154. long result = tx.next_run - ty.next_run;
  155. return result > 0 ? 1 : result < 0 ? -1 : 0;
  156. }
  157. }
  158. sealed class Scheduler {
  159. static Scheduler instance;
  160. SortedList list;
  161. static Scheduler ()
  162. {
  163. instance = new Scheduler ();
  164. }
  165. public static Scheduler Instance {
  166. get { return instance; }
  167. }
  168. private Scheduler ()
  169. {
  170. list = new SortedList (new TimerComparer (), 1024);
  171. Thread thread = new Thread (SchedulerThread);
  172. thread.IsBackground = true;
  173. thread.Start ();
  174. }
  175. public void Remove (Timer timer)
  176. {
  177. // We do not keep brand new items or those with no due time.
  178. if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
  179. return;
  180. lock (this) {
  181. // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
  182. // No need to Pulse ()
  183. InternalRemove (timer);
  184. }
  185. }
  186. public void Change (Timer timer, long new_next_run)
  187. {
  188. lock (this) {
  189. InternalRemove (timer);
  190. if (new_next_run == Int64.MaxValue) {
  191. timer.next_run = new_next_run;
  192. return;
  193. }
  194. if (!timer.disposed) {
  195. // We should only change next_run after removing and before adding
  196. timer.next_run = new_next_run;
  197. Add (timer);
  198. // If this timer is next in line, wake up the scheduler
  199. if (list.GetByIndex (0) == timer)
  200. Monitor.Pulse (this);
  201. }
  202. }
  203. }
  204. // This should be the only caller to list.Add!
  205. void Add (Timer timer)
  206. {
  207. // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
  208. int idx = list.IndexOfKey (timer);
  209. if (idx != -1) {
  210. bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
  211. while (true) {
  212. idx++;
  213. if (up)
  214. timer.next_run++;
  215. else
  216. timer.next_run--;
  217. if (idx >= list.Count)
  218. break;
  219. Timer t2 = (Timer) list.GetByIndex (idx);
  220. if (t2.next_run != timer.next_run)
  221. break;
  222. }
  223. }
  224. list.Add (timer, timer);
  225. //PrintList ();
  226. }
  227. int InternalRemove (Timer timer)
  228. {
  229. int idx = list.IndexOfKey (timer);
  230. if (idx >= 0)
  231. list.RemoveAt (idx);
  232. return idx;
  233. }
  234. void SchedulerThread ()
  235. {
  236. Thread.CurrentThread.Name = "Timer-Scheduler";
  237. ArrayList new_time = new ArrayList (512);
  238. while (true) {
  239. long ticks = DateTime.GetTimeMonotonic ();
  240. lock (this) {
  241. //PrintList ();
  242. int i;
  243. int count = list.Count;
  244. for (i = 0; i < count; i++) {
  245. Timer timer = (Timer) list.GetByIndex (i);
  246. if (timer.next_run > ticks)
  247. break;
  248. list.RemoveAt (i);
  249. count--;
  250. i--;
  251. ThreadPool.QueueUserWorkItem (new WaitCallback (timer.callback), timer.state);
  252. long period = timer.period_ms;
  253. long due_time = timer.due_time_ms;
  254. bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
  255. if (no_more) {
  256. timer.next_run = Int64.MaxValue;
  257. } else {
  258. timer.next_run = DateTime.GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
  259. new_time.Add (timer);
  260. }
  261. }
  262. // Reschedule timers with a new due time
  263. count = new_time.Count;
  264. for (i = 0; i < count; i++) {
  265. Timer timer = (Timer) new_time [i];
  266. Add (timer);
  267. }
  268. new_time.Clear ();
  269. ShrinkIfNeeded (new_time, 512);
  270. // Shrink the list
  271. int capacity = list.Capacity;
  272. count = list.Count;
  273. if (capacity > 1024 && count > 0 && (capacity / count) > 3)
  274. list.Capacity = count * 2;
  275. long min_next_run = Int64.MaxValue;
  276. if (list.Count > 0)
  277. min_next_run = ((Timer) list.GetByIndex (0)).next_run;
  278. //PrintList ();
  279. int ms_wait = -1;
  280. if (min_next_run != Int64.MaxValue) {
  281. long diff = min_next_run - DateTime.GetTimeMonotonic ();
  282. ms_wait = (int)(diff / TimeSpan.TicksPerMillisecond);
  283. if (ms_wait < 0)
  284. ms_wait = 0;
  285. }
  286. // Wait until due time or a timer is changed and moves from/to the first place in the list.
  287. Monitor.Wait (this, ms_wait);
  288. }
  289. }
  290. }
  291. void ShrinkIfNeeded (ArrayList list, int initial)
  292. {
  293. int capacity = list.Capacity;
  294. int count = list.Count;
  295. if (capacity > initial && count > 0 && (capacity / count) > 3)
  296. list.Capacity = count * 2;
  297. }
  298. /*
  299. void PrintList ()
  300. {
  301. Console.WriteLine ("BEGIN--");
  302. for (int i = 0; i < list.Count; i++) {
  303. Timer timer = (Timer) list.GetByIndex (i);
  304. Console.WriteLine ("{0}: {1}", i, timer.next_run);
  305. }
  306. Console.WriteLine ("END----");
  307. }
  308. */
  309. }
  310. }
  311. }