Timer.cs 11 KB

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