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;
34 namespace System.Threading
37 public sealed class Timer
38 : MarshalByRefObject, IDisposable
40 static readonly Scheduler scheduler = Scheduler.Instance;
41 #region Timer instance fields
42 TimerCallback callback;
46 long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
49 public Timer (TimerCallback callback, object state, int dueTime, int period)
51 Init (callback, state, dueTime, period);
54 public Timer (TimerCallback callback, object state, long dueTime, long period)
56 Init (callback, state, dueTime, period);
59 public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
61 Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
65 public Timer (TimerCallback callback, object state, uint dueTime, uint period)
67 // convert all values to long - with a special case for -1 / 0xffffffff
68 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
69 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
70 Init (callback, state, d, p);
73 public Timer (TimerCallback callback)
75 Init (callback, this, Timeout.Infinite, Timeout.Infinite);
78 void Init (TimerCallback callback, object state, long dueTime, long period)
81 throw new ArgumentNullException ("callback");
83 this.callback = callback;
86 Change (dueTime, period, true);
89 public bool Change (int dueTime, int period)
91 return Change (dueTime, period, false);
94 public bool Change (TimeSpan dueTime, TimeSpan period)
96 return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
100 public bool Change (uint dueTime, uint period)
102 // convert all values to long - with a special case for -1 / 0xffffffff
103 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
104 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
105 return Change (d, p, false);
108 public void Dispose ()
114 scheduler.Remove (this);
117 public bool Change (long dueTime, long period)
119 return Change (dueTime, period, false);
122 const long MaxValue = UInt32.MaxValue - 1;
124 bool Change (long dueTime, long period, bool first)
126 if (dueTime > MaxValue)
127 throw new ArgumentOutOfRangeException ("dueTime", "Due time too large");
129 if (period > MaxValue)
130 throw new ArgumentOutOfRangeException ("period", "Period too large");
132 // Timeout.Infinite == -1, so this accept everything greater than -1
133 if (dueTime < Timeout.Infinite)
134 throw new ArgumentOutOfRangeException ("dueTime");
136 if (period < Timeout.Infinite)
137 throw new ArgumentOutOfRangeException ("period");
142 due_time_ms = dueTime;
147 } else if (dueTime < 0) { // Infinite == -1
149 /* No need to call Change () */
155 nr = dueTime * TimeSpan.TicksPerMillisecond + DateTime.GetTimeMonotonic ();
158 scheduler.Change (this, nr);
162 public bool Dispose (WaitHandle notifyObject)
164 if (notifyObject == null)
165 throw new ArgumentNullException ("notifyObject");
167 NativeEventCalls.SetEvent_internal (notifyObject.Handle);
171 sealed class TimerComparer : IComparer {
172 public int Compare (object x, object y)
174 Timer tx = (x as Timer);
177 Timer ty = (y as Timer);
180 long result = tx.next_run - ty.next_run;
182 return x == y ? 0 : -1;
183 return result > 0 ? 1 : -1;
187 sealed class Scheduler {
188 static Scheduler instance;
190 ManualResetEvent changed;
194 instance = new Scheduler ();
197 public static Scheduler Instance {
198 get { return instance; }
203 changed = new ManualResetEvent (false);
204 list = new SortedList (new TimerComparer (), 1024);
205 Thread thread = new Thread (SchedulerThread);
206 thread.IsBackground = true;
210 public void Remove (Timer timer)
212 // We do not keep brand new items or those with no due time.
213 if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
217 // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
218 // No need to Pulse ()
219 InternalRemove (timer);
223 public void Change (Timer timer, long new_next_run)
227 InternalRemove (timer);
228 if (new_next_run == Int64.MaxValue) {
229 timer.next_run = new_next_run;
233 if (!timer.disposed) {
234 // We should only change next_run after removing and before adding
235 timer.next_run = new_next_run;
237 // If this timer is next in line, wake up the scheduler
238 wake = (list.GetByIndex (0) == timer);
245 // lock held by caller
246 int FindByDueTime (long nr)
249 int max = list.Count - 1;
255 Timer t = (Timer) list.GetByIndex (min);
256 if (t.next_run == nr)
266 int half = min + ((max - min) >> 1);
267 Timer t = (Timer) list.GetByIndex (half);
268 if (nr == t.next_run)
279 // This should be the only caller to list.Add!
280 void Add (Timer timer)
282 // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
283 // Do not use list.IndexOfKey here. See bug #648130
284 int idx = FindByDueTime (timer.next_run);
286 bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
294 if (idx >= list.Count)
296 Timer t2 = (Timer) list.GetByIndex (idx);
297 if (t2.next_run != timer.next_run)
301 list.Add (timer, timer);
305 int InternalRemove (Timer timer)
307 int idx = list.IndexOfKey (timer);
313 static WaitCallback TimerCaller = new WaitCallback (TimerCB);
314 static void TimerCB (object o)
316 Timer timer = (Timer) o;
318 timer.callback (timer.state);
322 void SchedulerThread ()
324 Thread.CurrentThread.Name = "Timer-Scheduler";
325 ArrayList new_time = new ArrayList (512);
328 long ticks = DateTime.GetTimeMonotonic ();
333 int count = list.Count;
334 for (i = 0; i < count; i++) {
335 Timer timer = (Timer) list.GetByIndex (i);
336 if (timer.next_run > ticks)
342 ThreadPool.UnsafeQueueUserWorkItem (TimerCaller, timer);
343 long period = timer.period_ms;
344 long due_time = timer.due_time_ms;
345 bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
347 timer.next_run = Int64.MaxValue;
349 timer.next_run = DateTime.GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
350 new_time.Add (timer);
354 // Reschedule timers with a new due time
355 count = new_time.Count;
356 for (i = 0; i < count; i++) {
357 Timer timer = (Timer) new_time [i];
361 ShrinkIfNeeded (new_time, 512);
364 int capacity = list.Capacity;
366 if (capacity > 1024 && count > 0 && (capacity / count) > 3)
367 list.Capacity = count * 2;
369 long min_next_run = Int64.MaxValue;
371 min_next_run = ((Timer) list.GetByIndex (0)).next_run;
375 if (min_next_run != Int64.MaxValue) {
376 long diff = (min_next_run - DateTime.GetTimeMonotonic ()) / TimeSpan.TicksPerMillisecond;
377 if (diff > Int32.MaxValue)
378 ms_wait = Int32.MaxValue - 1;
380 ms_wait = (int)(diff);
386 // Wait until due time or a timer is changed and moves from/to the first place in the list.
387 changed.WaitOne (ms_wait);
391 void ShrinkIfNeeded (ArrayList list, int initial)
393 int capacity = list.Capacity;
394 int count = list.Count;
395 if (capacity > initial && count > 0 && (capacity / count) > 3)
396 list.Capacity = count * 2;
402 Console.WriteLine ("BEGIN--");
403 for (int i = 0; i < list.Count; i++) {
404 Timer timer = (Timer) list.GetByIndex (i);
405 Console.WriteLine ("{0}: {1}", i, timer.next_run);
407 Console.WriteLine ("END----");