Timer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 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 readonly Scheduler instance = new Scheduler ();
  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. public static Scheduler Instance {
  242. get { return instance; }
  243. }
  244. private Scheduler ()
  245. {
  246. list = new SortedList (new TimerComparer (), 1024);
  247. InitScheduler ();
  248. }
  249. public void Remove (Timer timer)
  250. {
  251. // We do not keep brand new items or those with no due time.
  252. if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
  253. return;
  254. lock (this) {
  255. // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
  256. // No need to Pulse ()
  257. InternalRemove (timer);
  258. }
  259. }
  260. public void Change (Timer timer, long new_next_run)
  261. {
  262. bool wake = false;
  263. lock (this) {
  264. InternalRemove (timer);
  265. if (new_next_run == Int64.MaxValue) {
  266. timer.next_run = new_next_run;
  267. return;
  268. }
  269. if (!timer.disposed) {
  270. // We should only change next_run after removing and before adding
  271. timer.next_run = new_next_run;
  272. Add (timer);
  273. // If this timer is next in line, wake up the scheduler
  274. wake = (list.GetByIndex (0) == timer);
  275. }
  276. }
  277. if (wake)
  278. WakeupScheduler();
  279. }
  280. // lock held by caller
  281. int FindByDueTime (long nr)
  282. {
  283. int min = 0;
  284. int max = list.Count - 1;
  285. if (max < 0)
  286. return -1;
  287. if (max < 20) {
  288. while (min <= max) {
  289. Timer t = (Timer) list.GetByIndex (min);
  290. if (t.next_run == nr)
  291. return min;
  292. if (t.next_run > nr)
  293. return -1;
  294. min++;
  295. }
  296. return -1;
  297. }
  298. while (min <= max) {
  299. int half = min + ((max - min) >> 1);
  300. Timer t = (Timer) list.GetByIndex (half);
  301. if (nr == t.next_run)
  302. return half;
  303. if (nr > t.next_run)
  304. min = half + 1;
  305. else
  306. max = half - 1;
  307. }
  308. return -1;
  309. }
  310. // This should be the only caller to list.Add!
  311. void Add (Timer timer)
  312. {
  313. // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
  314. // Do not use list.IndexOfKey here. See bug #648130
  315. int idx = FindByDueTime (timer.next_run);
  316. if (idx != -1) {
  317. bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
  318. while (true) {
  319. idx++;
  320. if (up)
  321. timer.next_run++;
  322. else
  323. timer.next_run--;
  324. if (idx >= list.Count)
  325. break;
  326. Timer t2 = (Timer) list.GetByIndex (idx);
  327. if (t2.next_run != timer.next_run)
  328. break;
  329. }
  330. }
  331. list.Add (timer, timer);
  332. //PrintList ();
  333. }
  334. int InternalRemove (Timer timer)
  335. {
  336. int idx = list.IndexOfKey (timer);
  337. if (idx >= 0)
  338. list.RemoveAt (idx);
  339. return idx;
  340. }
  341. static void TimerCB (object o)
  342. {
  343. Timer timer = (Timer) o;
  344. timer.callback (timer.state);
  345. }
  346. int RunSchedulerLoop (List<Timer> new_time) {
  347. int ms_wait = -1;
  348. int i;
  349. int count = list.Count;
  350. long ticks = GetTimeMonotonic ();
  351. for (i = 0; i < count; i++) {
  352. Timer timer = (Timer) list.GetByIndex (i);
  353. if (timer.next_run > ticks)
  354. break;
  355. list.RemoveAt (i);
  356. count--;
  357. i--;
  358. ThreadPool.UnsafeQueueUserWorkItem (TimerCB, timer);
  359. long period = timer.period_ms;
  360. long due_time = timer.due_time_ms;
  361. bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
  362. if (no_more) {
  363. timer.next_run = Int64.MaxValue;
  364. } else {
  365. timer.next_run = GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
  366. new_time.Add (timer);
  367. }
  368. }
  369. // Reschedule timers with a new due time
  370. count = new_time.Count;
  371. for (i = 0; i < count; i++) {
  372. Timer timer = new_time [i];
  373. Add (timer);
  374. }
  375. new_time.Clear ();
  376. ShrinkIfNeeded (new_time, 512);
  377. // Shrink the list
  378. int capacity = list.Capacity;
  379. count = list.Count;
  380. if (capacity > 1024 && count > 0 && (capacity / count) > 3)
  381. list.Capacity = count * 2;
  382. long min_next_run = Int64.MaxValue;
  383. if (list.Count > 0)
  384. min_next_run = ((Timer) list.GetByIndex (0)).next_run;
  385. //PrintList ();
  386. ms_wait = -1;
  387. if (min_next_run != Int64.MaxValue) {
  388. long diff = (min_next_run - GetTimeMonotonic ()) / TimeSpan.TicksPerMillisecond;
  389. if (diff > Int32.MaxValue)
  390. ms_wait = Int32.MaxValue - 1;
  391. else {
  392. ms_wait = (int)(diff);
  393. if (ms_wait < 0)
  394. ms_wait = 0;
  395. }
  396. }
  397. return ms_wait;
  398. }
  399. void ShrinkIfNeeded (List<Timer> list, int initial)
  400. {
  401. int capacity = list.Capacity;
  402. int count = list.Count;
  403. if (capacity > initial && count > 0 && (capacity / count) > 3)
  404. list.Capacity = count * 2;
  405. }
  406. /*
  407. void PrintList ()
  408. {
  409. Console.WriteLine ("BEGIN--");
  410. for (int i = 0; i < list.Count; i++) {
  411. Timer timer = (Timer) list.GetByIndex (i);
  412. Console.WriteLine ("{0}: {1}", i, timer.next_run);
  413. }
  414. Console.WriteLine ("END----");
  415. }
  416. */
  417. }
  418. }
  419. }