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 : MarshalByRefObject, IDisposable
39 static Scheduler scheduler = Scheduler.Instance;
40 #region Timer instance fields
41 TimerCallback callback;
45 long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
48 public Timer (TimerCallback callback, object state, int dueTime, int period)
50 Init (callback, state, dueTime, period);
53 public Timer (TimerCallback callback, object state, long dueTime, long period)
55 Init (callback, state, dueTime, period);
58 public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
60 Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
64 public Timer (TimerCallback callback, object state, uint dueTime, uint period)
66 // convert all values to long - with a special case for -1 / 0xffffffff
67 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
68 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
69 Init (callback, state, d, p);
72 public Timer (TimerCallback callback)
74 Init (callback, this, Timeout.Infinite, Timeout.Infinite);
77 void Init (TimerCallback callback, object state, long dueTime, long period)
80 throw new ArgumentNullException ("callback");
82 this.callback = callback;
85 Change (dueTime, period, true);
88 public bool Change (int dueTime, int period)
90 return Change (dueTime, period, false);
93 public bool Change (TimeSpan dueTime, TimeSpan period)
95 return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
99 public bool Change (uint dueTime, uint period)
101 // convert all values to long - with a special case for -1 / 0xffffffff
102 long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
103 long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
104 return Change (d, p, false);
107 public void Dispose ()
113 scheduler.Remove (this);
116 public bool Change (long dueTime, long period)
118 return Change (dueTime, period, false);
121 const long MaxValue = UInt32.MaxValue - 1;
123 bool Change (long dueTime, long period, bool first)
125 if (dueTime > MaxValue)
126 throw new ArgumentOutOfRangeException ("Due time too large");
128 if (period > MaxValue)
129 throw new ArgumentOutOfRangeException ("Period too large");
131 // Timeout.Infinite == -1, so this accept everything greater than -1
132 if (dueTime < Timeout.Infinite)
133 throw new ArgumentOutOfRangeException ("dueTime");
135 if (period < Timeout.Infinite)
136 throw new ArgumentOutOfRangeException ("period");
141 due_time_ms = dueTime;
146 } else if (dueTime < 0) { // Infinite == -1
148 /* No need to call Change () */
154 nr = dueTime * TimeSpan.TicksPerMillisecond + DateTime.GetTimeMonotonic ();
157 scheduler.Change (this, nr);
161 public bool Dispose (WaitHandle notifyObject)
163 if (notifyObject == null)
164 throw new ArgumentNullException ("notifyObject");
166 NativeEventCalls.SetEvent_internal (notifyObject.Handle);
170 sealed class TimerComparer : IComparer {
171 public int Compare (object x, object y)
173 Timer tx = (x as Timer);
176 Timer ty = (y as Timer);
179 long result = tx.next_run - ty.next_run;
181 return x == y ? 0 : -1;
182 return result > 0 ? 1 : -1;
186 sealed class Scheduler {
187 static Scheduler instance;
189 ManualResetEvent changed;
193 instance = new Scheduler ();
196 public static Scheduler Instance {
197 get { return instance; }
202 changed = new ManualResetEvent (false);
203 list = new SortedList (new TimerComparer (), 1024);
204 Thread thread = new Thread (SchedulerThread);
205 thread.IsBackground = true;
209 public void Remove (Timer timer)
211 // We do not keep brand new items or those with no due time.
212 if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
216 // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
217 // No need to Pulse ()
218 InternalRemove (timer);
222 public void Change (Timer timer, long new_next_run)
226 InternalRemove (timer);
227 if (new_next_run == Int64.MaxValue) {
228 timer.next_run = new_next_run;
232 if (!timer.disposed) {
233 // We should only change next_run after removing and before adding
234 timer.next_run = new_next_run;
236 // If this timer is next in line, wake up the scheduler
237 wake = (list.GetByIndex (0) == timer);
244 // lock held by caller
245 int FindByDueTime (long nr)
248 int max = list.Count - 1;
254 Timer t = (Timer) list.GetByIndex (min);
255 if (t.next_run == nr)
265 int half = min + ((max - min) >> 1);
266 Timer t = (Timer) list.GetByIndex (half);
267 if (nr == t.next_run)
278 // This should be the only caller to list.Add!
279 void Add (Timer timer)
281 // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
282 // Do not use list.IndexOfKey here. See bug #648130
283 int idx = FindByDueTime (timer.next_run);
285 bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
293 if (idx >= list.Count)
295 Timer t2 = (Timer) list.GetByIndex (idx);
296 if (t2.next_run != timer.next_run)
300 list.Add (timer, timer);
304 int InternalRemove (Timer timer)
306 int idx = list.IndexOfKey (timer);
312 static WaitCallback TimerCaller = new WaitCallback (TimerCB);
313 static void TimerCB (object o)
315 Timer timer = (Timer) o;
317 timer.callback (timer.state);
321 void SchedulerThread ()
323 Thread.CurrentThread.Name = "Timer-Scheduler";
324 ArrayList new_time = new ArrayList (512);
327 long ticks = DateTime.GetTimeMonotonic ();
332 int count = list.Count;
333 for (i = 0; i < count; i++) {
334 Timer timer = (Timer) list.GetByIndex (i);
335 if (timer.next_run > ticks)
342 ThreadPool.QueueUserWorkItem (TimerCaller, timer);
344 ThreadPool.UnsafeQueueUserWorkItem (TimerCaller, timer);
346 long period = timer.period_ms;
347 long due_time = timer.due_time_ms;
348 bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
350 timer.next_run = Int64.MaxValue;
352 timer.next_run = DateTime.GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
353 new_time.Add (timer);
357 // Reschedule timers with a new due time
358 count = new_time.Count;
359 for (i = 0; i < count; i++) {
360 Timer timer = (Timer) new_time [i];
364 ShrinkIfNeeded (new_time, 512);
367 int capacity = list.Capacity;
369 if (capacity > 1024 && count > 0 && (capacity / count) > 3)
370 list.Capacity = count * 2;
372 long min_next_run = Int64.MaxValue;
374 min_next_run = ((Timer) list.GetByIndex (0)).next_run;
378 if (min_next_run != Int64.MaxValue) {
379 long diff = min_next_run - DateTime.GetTimeMonotonic ();
380 ms_wait = (int)(diff / TimeSpan.TicksPerMillisecond);
385 // Wait until due time or a timer is changed and moves from/to the first place in the list.
386 changed.WaitOne (ms_wait);
390 void ShrinkIfNeeded (ArrayList list, int initial)
392 int capacity = list.Capacity;
393 int count = list.Count;
394 if (capacity > initial && count > 0 && (capacity / count) > 3)
395 list.Capacity = count * 2;
401 Console.WriteLine ("BEGIN--");
402 for (int i = 0; i < list.Count; i++) {
403 Timer timer = (Timer) list.GetByIndex (i);
404 Console.WriteLine ("{0}: {1}", i, timer.next_run);
406 Console.WriteLine ("END----");