Timer.cs 11 KB

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