Timer.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. if (result == 0)
  156. return x == y ? 0 : -1;
  157. return result > 0 ? 1 : -1;
  158. }
  159. }
  160. sealed class Scheduler {
  161. static Scheduler instance;
  162. SortedList list;
  163. static Scheduler ()
  164. {
  165. instance = new Scheduler ();
  166. }
  167. public static Scheduler Instance {
  168. get { return instance; }
  169. }
  170. private Scheduler ()
  171. {
  172. list = new SortedList (new TimerComparer (), 1024);
  173. Thread thread = new Thread (SchedulerThread);
  174. thread.IsBackground = true;
  175. thread.Start ();
  176. }
  177. public void Remove (Timer timer)
  178. {
  179. // We do not keep brand new items or those with no due time.
  180. if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
  181. return;
  182. lock (this) {
  183. // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
  184. // No need to Pulse ()
  185. InternalRemove (timer);
  186. }
  187. }
  188. public void Change (Timer timer, long new_next_run)
  189. {
  190. lock (this) {
  191. InternalRemove (timer);
  192. if (new_next_run == Int64.MaxValue) {
  193. timer.next_run = new_next_run;
  194. return;
  195. }
  196. if (!timer.disposed) {
  197. // We should only change next_run after removing and before adding
  198. timer.next_run = new_next_run;
  199. Add (timer);
  200. // If this timer is next in line, wake up the scheduler
  201. if (list.GetByIndex (0) == timer)
  202. Monitor.Pulse (this);
  203. }
  204. }
  205. }
  206. // lock held by caller
  207. int FindByDueTime (long nr)
  208. {
  209. int min = 0;
  210. int max = list.Count - 1;
  211. if (max < 0)
  212. return -1;
  213. if (max < 20) {
  214. while (min <= max) {
  215. Timer t = (Timer) list.GetByIndex (min);
  216. if (t.next_run == nr)
  217. return min;
  218. if (t.next_run > nr)
  219. return -1;
  220. min++;
  221. }
  222. return -1;
  223. }
  224. while (min <= max) {
  225. int half = min + ((max - min) >> 1);
  226. Timer t = (Timer) list.GetByIndex (half);
  227. if (nr == t.next_run)
  228. return half;
  229. if (nr > t.next_run)
  230. min = half + 1;
  231. else
  232. max = half - 1;
  233. }
  234. return -1;
  235. }
  236. // This should be the only caller to list.Add!
  237. void Add (Timer timer)
  238. {
  239. // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
  240. // Do not use list.IndexOfKey here. See bug #648130
  241. int idx = FindByDueTime (timer.next_run);
  242. if (idx != -1) {
  243. bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
  244. while (true) {
  245. idx++;
  246. if (up)
  247. timer.next_run++;
  248. else
  249. timer.next_run--;
  250. if (idx >= list.Count)
  251. break;
  252. Timer t2 = (Timer) list.GetByIndex (idx);
  253. if (t2.next_run != timer.next_run)
  254. break;
  255. }
  256. }
  257. list.Add (timer, timer);
  258. //PrintList ();
  259. }
  260. int InternalRemove (Timer timer)
  261. {
  262. int idx = list.IndexOfKey (timer);
  263. if (idx >= 0)
  264. list.RemoveAt (idx);
  265. return idx;
  266. }
  267. void SchedulerThread ()
  268. {
  269. Thread.CurrentThread.Name = "Timer-Scheduler";
  270. ArrayList new_time = new ArrayList (512);
  271. while (true) {
  272. long ticks = DateTime.GetTimeMonotonic ();
  273. lock (this) {
  274. //PrintList ();
  275. int i;
  276. int count = list.Count;
  277. for (i = 0; i < count; i++) {
  278. Timer timer = (Timer) list.GetByIndex (i);
  279. if (timer.next_run > ticks)
  280. break;
  281. list.RemoveAt (i);
  282. count--;
  283. i--;
  284. ThreadPool.QueueUserWorkItem (new WaitCallback (data => {
  285. try {
  286. timer.callback (data);
  287. } catch {}
  288. }), timer.state);
  289. long period = timer.period_ms;
  290. long due_time = timer.due_time_ms;
  291. bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
  292. if (no_more) {
  293. timer.next_run = Int64.MaxValue;
  294. } else {
  295. timer.next_run = DateTime.GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
  296. new_time.Add (timer);
  297. }
  298. }
  299. // Reschedule timers with a new due time
  300. count = new_time.Count;
  301. for (i = 0; i < count; i++) {
  302. Timer timer = (Timer) new_time [i];
  303. Add (timer);
  304. }
  305. new_time.Clear ();
  306. ShrinkIfNeeded (new_time, 512);
  307. // Shrink the list
  308. int capacity = list.Capacity;
  309. count = list.Count;
  310. if (capacity > 1024 && count > 0 && (capacity / count) > 3)
  311. list.Capacity = count * 2;
  312. long min_next_run = Int64.MaxValue;
  313. if (list.Count > 0)
  314. min_next_run = ((Timer) list.GetByIndex (0)).next_run;
  315. //PrintList ();
  316. int ms_wait = -1;
  317. if (min_next_run != Int64.MaxValue) {
  318. long diff = min_next_run - DateTime.GetTimeMonotonic ();
  319. ms_wait = (int)(diff / TimeSpan.TicksPerMillisecond);
  320. if (ms_wait < 0)
  321. ms_wait = 0;
  322. }
  323. // Wait until due time or a timer is changed and moves from/to the first place in the list.
  324. Monitor.Wait (this, ms_wait);
  325. }
  326. }
  327. }
  328. void ShrinkIfNeeded (ArrayList list, int initial)
  329. {
  330. int capacity = list.Capacity;
  331. int count = list.Count;
  332. if (capacity > initial && count > 0 && (capacity / count) > 3)
  333. list.Capacity = count * 2;
  334. }
  335. /*
  336. void PrintList ()
  337. {
  338. Console.WriteLine ("BEGIN--");
  339. for (int i = 0; i < list.Count; i++) {
  340. Timer timer = (Timer) list.GetByIndex (i);
  341. Console.WriteLine ("{0}: {1}", i, timer.next_run);
  342. }
  343. Console.WriteLine ("END----");
  344. }
  345. */
  346. }
  347. }
  348. }