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;
34 using System.Runtime.CompilerServices;
36 namespace System.Threading
39 public sealed class Timer
40 : MarshalByRefObject, IDisposable
42 static readonly Scheduler scheduler = Scheduler.Instance;
43 #region Timer instance fields
44 TimerCallback callback;
48 long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
51 public Timer (TimerCallback callback, object state, int dueTime, int period)
53 Init (callback, state, dueTime, period);
56 public Timer (TimerCallback callback, object state, long dueTime, long period)
58 Init (callback, state, dueTime, period);
61 public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
63 Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
67 public Timer (TimerCallback callback, object state, uint dueTime, uint period)
69 // convert all values to long - with a special case for -1 / 0xffffffff
70 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
71 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
72 Init (callback, state, d, p);
75 public Timer (TimerCallback callback)
77 Init (callback, this, Timeout.Infinite, Timeout.Infinite);
80 void Init (TimerCallback callback, object state, long dueTime, long period)
83 throw new ArgumentNullException ("callback");
85 this.callback = callback;
88 Change (dueTime, period, true);
91 public bool Change (int dueTime, int period)
93 return Change (dueTime, period, false);
96 public bool Change (TimeSpan dueTime, TimeSpan period)
98 return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
101 [CLSCompliant(false)]
102 public bool Change (uint dueTime, uint period)
104 // convert all values to long - with a special case for -1 / 0xffffffff
105 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
106 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
107 return Change (d, p, false);
110 public void Dispose ()
116 scheduler.Remove (this);
119 public bool Change (long dueTime, long period)
121 return Change (dueTime, period, false);
124 const long MaxValue = UInt32.MaxValue - 1;
126 bool Change (long dueTime, long period, bool first)
128 if (dueTime > MaxValue)
129 throw new ArgumentOutOfRangeException ("dueTime", "Due time too large");
131 if (period > MaxValue)
132 throw new ArgumentOutOfRangeException ("period", "Period too large");
134 // Timeout.Infinite == -1, so this accept everything greater than -1
135 if (dueTime < Timeout.Infinite)
136 throw new ArgumentOutOfRangeException ("dueTime");
138 if (period < Timeout.Infinite)
139 throw new ArgumentOutOfRangeException ("period");
144 due_time_ms = dueTime;
149 } else if (dueTime < 0) { // Infinite == -1
151 /* No need to call Change () */
157 nr = dueTime * TimeSpan.TicksPerMillisecond + GetTimeMonotonic ();
160 scheduler.Change (this, nr);
164 public bool Dispose (WaitHandle notifyObject)
166 if (notifyObject == null)
167 throw new ArgumentNullException ("notifyObject");
169 NativeEventCalls.SetEvent_internal (notifyObject.Handle);
173 // extracted from ../../../../external/referencesource/mscorlib/system/threading/timer.cs
174 internal void KeepRootedWhileScheduled()
178 // TODO: Environment.TickCount should be enough as is everywhere else
179 [MethodImplAttribute(MethodImplOptions.InternalCall)]
180 static extern long GetTimeMonotonic ();
182 sealed class TimerComparer : IComparer {
183 public int Compare (object x, object y)
185 Timer tx = (x as Timer);
188 Timer ty = (y as Timer);
191 long result = tx.next_run - ty.next_run;
193 return x == y ? 0 : -1;
194 return result > 0 ? 1 : -1;
198 sealed class Scheduler {
199 static Scheduler instance;
201 ManualResetEvent changed;
205 instance = new Scheduler ();
208 public static Scheduler Instance {
209 get { return instance; }
214 changed = new ManualResetEvent (false);
215 list = new SortedList (new TimerComparer (), 1024);
216 Thread thread = new Thread (SchedulerThread);
217 thread.IsBackground = true;
221 public void Remove (Timer timer)
223 // We do not keep brand new items or those with no due time.
224 if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
228 // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
229 // No need to Pulse ()
230 InternalRemove (timer);
234 public void Change (Timer timer, long new_next_run)
238 InternalRemove (timer);
239 if (new_next_run == Int64.MaxValue) {
240 timer.next_run = new_next_run;
244 if (!timer.disposed) {
245 // We should only change next_run after removing and before adding
246 timer.next_run = new_next_run;
248 // If this timer is next in line, wake up the scheduler
249 wake = (list.GetByIndex (0) == timer);
256 // lock held by caller
257 int FindByDueTime (long nr)
260 int max = list.Count - 1;
266 Timer t = (Timer) list.GetByIndex (min);
267 if (t.next_run == nr)
277 int half = min + ((max - min) >> 1);
278 Timer t = (Timer) list.GetByIndex (half);
279 if (nr == t.next_run)
290 // This should be the only caller to list.Add!
291 void Add (Timer timer)
293 // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
294 // Do not use list.IndexOfKey here. See bug #648130
295 int idx = FindByDueTime (timer.next_run);
297 bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
305 if (idx >= list.Count)
307 Timer t2 = (Timer) list.GetByIndex (idx);
308 if (t2.next_run != timer.next_run)
312 list.Add (timer, timer);
316 int InternalRemove (Timer timer)
318 int idx = list.IndexOfKey (timer);
324 static void TimerCB (object o)
326 Timer timer = (Timer) o;
327 timer.callback (timer.state);
330 void SchedulerThread ()
332 Thread.CurrentThread.Name = "Timer-Scheduler";
333 var new_time = new List<Timer> (512);
336 long ticks = GetTimeMonotonic ();
341 int count = list.Count;
342 for (i = 0; i < count; i++) {
343 Timer timer = (Timer) list.GetByIndex (i);
344 if (timer.next_run > ticks)
350 ThreadPool.UnsafeQueueUserWorkItem (TimerCB, timer);
351 long period = timer.period_ms;
352 long due_time = timer.due_time_ms;
353 bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
355 timer.next_run = Int64.MaxValue;
357 timer.next_run = GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
358 new_time.Add (timer);
362 // Reschedule timers with a new due time
363 count = new_time.Count;
364 for (i = 0; i < count; i++) {
365 Timer timer = new_time [i];
369 ShrinkIfNeeded (new_time, 512);
372 int capacity = list.Capacity;
374 if (capacity > 1024 && count > 0 && (capacity / count) > 3)
375 list.Capacity = count * 2;
377 long min_next_run = Int64.MaxValue;
379 min_next_run = ((Timer) list.GetByIndex (0)).next_run;
383 if (min_next_run != Int64.MaxValue) {
384 long diff = (min_next_run - GetTimeMonotonic ()) / TimeSpan.TicksPerMillisecond;
385 if (diff > Int32.MaxValue)
386 ms_wait = Int32.MaxValue - 1;
388 ms_wait = (int)(diff);
394 // Wait until due time or a timer is changed and moves from/to the first place in the list.
395 changed.WaitOne (ms_wait);
399 void ShrinkIfNeeded (List<Timer> list, int initial)
401 int capacity = list.Capacity;
402 int count = list.Count;
403 if (capacity > initial && count > 0 && (capacity / count) > 3)
404 list.Capacity = count * 2;
410 Console.WriteLine ("BEGIN--");
411 for (int i = 0; i < list.Count; i++) {
412 Timer timer = (Timer) list.GetByIndex (i);
413 Console.WriteLine ("{0}: {1}", i, timer.next_run);
415 Console.WriteLine ("END----");