Timer.cs 11 KB

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