2 // System.Threading.Timer.cs
5 // Dick Porter (dick@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (C) 2001, 2002 Ximian, Inc. http://www.ximian.com
9 // Copyright (C) 2004-2009 Novell, Inc (http://www.novell.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
31 using System.Runtime.InteropServices;
32 using System.Collections.Generic;
33 using System.Collections;
35 namespace System.Threading
38 public sealed class Timer
39 : MarshalByRefObject, IDisposable
41 static readonly Scheduler scheduler = Scheduler.Instance;
42 #region Timer instance fields
43 TimerCallback callback;
47 long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
50 public Timer (TimerCallback callback, object state, int dueTime, int period)
52 Init (callback, state, dueTime, period);
55 public Timer (TimerCallback callback, object state, long dueTime, long period)
57 Init (callback, state, dueTime, period);
60 public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
62 Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
66 public Timer (TimerCallback callback, object state, uint dueTime, uint period)
68 // convert all values to long - with a special case for -1 / 0xffffffff
69 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
70 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
71 Init (callback, state, d, p);
74 public Timer (TimerCallback callback)
76 Init (callback, this, Timeout.Infinite, Timeout.Infinite);
79 void Init (TimerCallback callback, object state, long dueTime, long period)
82 throw new ArgumentNullException ("callback");
84 this.callback = callback;
87 Change (dueTime, period, true);
90 public bool Change (int dueTime, int period)
92 return Change (dueTime, period, false);
95 public bool Change (TimeSpan dueTime, TimeSpan period)
97 return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
100 [CLSCompliant(false)]
101 public bool Change (uint dueTime, uint period)
103 // convert all values to long - with a special case for -1 / 0xffffffff
104 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
105 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
106 return Change (d, p, false);
109 public void Dispose ()
115 scheduler.Remove (this);
118 public bool Change (long dueTime, long period)
120 return Change (dueTime, period, false);
123 const long MaxValue = UInt32.MaxValue - 1;
125 bool Change (long dueTime, long period, bool first)
127 if (dueTime > MaxValue)
128 throw new ArgumentOutOfRangeException ("dueTime", "Due time too large");
130 if (period > MaxValue)
131 throw new ArgumentOutOfRangeException ("period", "Period too large");
133 // Timeout.Infinite == -1, so this accept everything greater than -1
134 if (dueTime < Timeout.Infinite)
135 throw new ArgumentOutOfRangeException ("dueTime");
137 if (period < Timeout.Infinite)
138 throw new ArgumentOutOfRangeException ("period");
143 due_time_ms = dueTime;
148 } else if (dueTime < 0) { // Infinite == -1
150 /* No need to call Change () */
156 nr = dueTime * TimeSpan.TicksPerMillisecond + DateTime.GetTimeMonotonic ();
159 scheduler.Change (this, nr);
163 public bool Dispose (WaitHandle notifyObject)
165 if (notifyObject == null)
166 throw new ArgumentNullException ("notifyObject");
168 NativeEventCalls.SetEvent_internal (notifyObject.Handle);
172 sealed class TimerComparer : IComparer {
173 public int Compare (object x, object y)
175 Timer tx = (x as Timer);
178 Timer ty = (y as Timer);
181 long result = tx.next_run - ty.next_run;
183 return x == y ? 0 : -1;
184 return result > 0 ? 1 : -1;
188 sealed class Scheduler {
189 static Scheduler instance;
191 ManualResetEvent changed;
195 instance = new Scheduler ();
198 public static Scheduler Instance {
199 get { return instance; }
204 changed = new ManualResetEvent (false);
205 list = new SortedList (new TimerComparer (), 1024);
206 Thread thread = new Thread (SchedulerThread);
207 thread.IsBackground = true;
211 public void Remove (Timer timer)
213 // We do not keep brand new items or those with no due time.
214 if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
218 // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
219 // No need to Pulse ()
220 InternalRemove (timer);
224 public void Change (Timer timer, long new_next_run)
228 InternalRemove (timer);
229 if (new_next_run == Int64.MaxValue) {
230 timer.next_run = new_next_run;
234 if (!timer.disposed) {
235 // We should only change next_run after removing and before adding
236 timer.next_run = new_next_run;
238 // If this timer is next in line, wake up the scheduler
239 wake = (list.GetByIndex (0) == timer);
246 // lock held by caller
247 int FindByDueTime (long nr)
250 int max = list.Count - 1;
256 Timer t = (Timer) list.GetByIndex (min);
257 if (t.next_run == nr)
267 int half = min + ((max - min) >> 1);
268 Timer t = (Timer) list.GetByIndex (half);
269 if (nr == t.next_run)
280 // This should be the only caller to list.Add!
281 void Add (Timer timer)
283 // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
284 // Do not use list.IndexOfKey here. See bug #648130
285 int idx = FindByDueTime (timer.next_run);
287 bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
295 if (idx >= list.Count)
297 Timer t2 = (Timer) list.GetByIndex (idx);
298 if (t2.next_run != timer.next_run)
302 list.Add (timer, timer);
306 int InternalRemove (Timer timer)
308 int idx = list.IndexOfKey (timer);
314 static WaitCallback TimerCaller = new WaitCallback (TimerCB);
315 static void TimerCB (object o)
317 Timer timer = (Timer) o;
319 timer.callback (timer.state);
323 void SchedulerThread ()
325 Thread.CurrentThread.Name = "Timer-Scheduler";
326 var new_time = new List<Timer> (512);
329 long ticks = DateTime.GetTimeMonotonic ();
334 int count = list.Count;
335 for (i = 0; i < count; i++) {
336 Timer timer = (Timer) list.GetByIndex (i);
337 if (timer.next_run > ticks)
343 ThreadPool.UnsafeQueueUserWorkItem (TimerCaller, timer);
344 long period = timer.period_ms;
345 long due_time = timer.due_time_ms;
346 bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
348 timer.next_run = Int64.MaxValue;
350 timer.next_run = DateTime.GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
351 new_time.Add (timer);
355 // Reschedule timers with a new due time
356 count = new_time.Count;
357 for (i = 0; i < count; i++) {
358 Timer timer = new_time [i];
362 ShrinkIfNeeded (new_time, 512);
365 int capacity = list.Capacity;
367 if (capacity > 1024 && count > 0 && (capacity / count) > 3)
368 list.Capacity = count * 2;
370 long min_next_run = Int64.MaxValue;
372 min_next_run = ((Timer) list.GetByIndex (0)).next_run;
376 if (min_next_run != Int64.MaxValue) {
377 long diff = (min_next_run - DateTime.GetTimeMonotonic ()) / TimeSpan.TicksPerMillisecond;
378 if (diff > Int32.MaxValue)
379 ms_wait = Int32.MaxValue - 1;
381 ms_wait = (int)(diff);
387 // Wait until due time or a timer is changed and moves from/to the first place in the list.
388 changed.WaitOne (ms_wait);
392 void ShrinkIfNeeded (List<Timer> list, int initial)
394 int capacity = list.Capacity;
395 int count = list.Count;
396 if (capacity > initial && count > 0 && (capacity / count) > 3)
397 list.Capacity = count * 2;
403 Console.WriteLine ("BEGIN--");
404 for (int i = 0; i < list.Count; i++) {
405 Timer timer = (Timer) list.GetByIndex (i);
406 Console.WriteLine ("{0}: {1}", i, timer.next_run);
408 Console.WriteLine ("END----");