Timer.cs 12 KB

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