5d41f2388b99ae7df25e1e3c22cf0c96547df37e
[mono.git] / mcs / class / corlib / System.Threading / Timer.cs
1 //
2 // System.Threading.Timer.cs
3 //
4 // Authors:
5 //      Dick Porter (dick@ximian.com)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
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
31 using System.Runtime.InteropServices;
32 using System.Collections;
33
34 namespace System.Threading
35 {
36         [ComVisible (true)]
37         public sealed class Timer
38                 : MarshalByRefObject, IDisposable
39         {
40                 static readonly Scheduler scheduler = Scheduler.Instance;
41 #region Timer instance fields
42                 TimerCallback callback;
43                 object state;
44                 long due_time_ms;
45                 long period_ms;
46                 long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
47                 bool disposed;
48 #endregion
49                 public Timer (TimerCallback callback, object state, int dueTime, int period)
50                 {
51                         Init (callback, state, dueTime, period);
52                 }
53
54                 public Timer (TimerCallback callback, object state, long dueTime, long period)
55                 {
56                         Init (callback, state, dueTime, period);
57                 }
58
59                 public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
60                 {
61                         Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
62                 }
63
64                 [CLSCompliant(false)]
65                 public Timer (TimerCallback callback, object state, uint dueTime, uint period)
66                 {
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);
71                 }
72
73                 public Timer (TimerCallback callback)
74                 {
75                         Init (callback, this, Timeout.Infinite, Timeout.Infinite);
76                 }
77
78                 void Init (TimerCallback callback, object state, long dueTime, long period)
79                 {
80                         if (callback == null)
81                                 throw new ArgumentNullException ("callback");
82                         
83                         this.callback = callback;
84                         this.state = state;
85
86                         Change (dueTime, period, true);
87                 }
88
89                 public bool Change (int dueTime, int period)
90                 {
91                         return Change (dueTime, period, false);
92                 }
93
94                 public bool Change (TimeSpan dueTime, TimeSpan period)
95                 {
96                         return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
97                 }
98
99                 [CLSCompliant(false)]
100                 public bool Change (uint dueTime, uint period)
101                 {
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);
106                 }
107
108                 public void Dispose ()
109                 {
110                         if (disposed)
111                                 return;
112
113                         disposed = true;
114                         scheduler.Remove (this);
115                 }
116
117                 public bool Change (long dueTime, long period)
118                 {
119                         return Change (dueTime, period, false);
120                 }
121
122                 const long MaxValue = UInt32.MaxValue - 1;
123
124                 bool Change (long dueTime, long period, bool first)
125                 {
126                         if (dueTime > MaxValue)
127                                 throw new ArgumentOutOfRangeException ("dueTime", "Due time too large");
128
129                         if (period > MaxValue)
130                                 throw new ArgumentOutOfRangeException ("period", "Period too large");
131
132                         // Timeout.Infinite == -1, so this accept everything greater than -1
133                         if (dueTime < Timeout.Infinite)
134                                 throw new ArgumentOutOfRangeException ("dueTime");
135
136                         if (period < Timeout.Infinite)
137                                 throw new ArgumentOutOfRangeException ("period");
138
139                         if (disposed)
140                                 return false;
141
142                         due_time_ms = dueTime;
143                         period_ms = period;
144                         long nr;
145                         if (dueTime == 0) {
146                                 nr = 0; // Due now
147                         } else if (dueTime < 0) { // Infinite == -1
148                                 nr = long.MaxValue;
149                                 /* No need to call Change () */
150                                 if (first) {
151                                         next_run = nr;
152                                         return true;
153                                 }
154                         } else {
155                                 nr = dueTime * TimeSpan.TicksPerMillisecond + DateTime.GetTimeMonotonic ();
156                         }
157
158                         scheduler.Change (this, nr);
159                         return true;
160                 }
161
162                 public bool Dispose (WaitHandle notifyObject)
163                 {
164                         if (notifyObject == null)
165                                 throw new ArgumentNullException ("notifyObject");
166                         Dispose ();
167                         NativeEventCalls.SetEvent_internal (notifyObject.Handle);
168                         return true;
169                 }
170
171                 sealed class TimerComparer : IComparer {
172                         public int Compare (object x, object y)
173                         {
174                                 Timer tx = (x as Timer);
175                                 if (tx == null)
176                                         return -1;
177                                 Timer ty = (y as Timer);
178                                 if (ty == null)
179                                         return 1;
180                                 long result = tx.next_run - ty.next_run;
181                                 if (result == 0)
182                                         return x == y ? 0 : -1;
183                                 return result > 0 ? 1 : -1;
184                         }
185                 }
186
187                 sealed class Scheduler {
188                         static Scheduler instance;
189                         SortedList list;
190                         ManualResetEvent changed;
191
192                         static Scheduler ()
193                         {
194                                 instance = new Scheduler ();
195                         }
196
197                         public static Scheduler Instance {
198                                 get { return instance; }
199                         }
200
201                         private Scheduler ()
202                         {
203                                 changed = new ManualResetEvent (false);
204                                 list = new SortedList (new TimerComparer (), 1024);
205                                 Thread thread = new Thread (SchedulerThread);
206                                 thread.IsBackground = true;
207                                 thread.Start ();
208                         }
209
210                         public void Remove (Timer timer)
211                         {
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)
214                                         return;
215
216                                 lock (this) {
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);
220                                 }
221                         }
222
223                         public void Change (Timer timer, long new_next_run)
224                         {
225                                 bool wake = false;
226                                 lock (this) {
227                                         InternalRemove (timer);
228                                         if (new_next_run == Int64.MaxValue) {
229                                                 timer.next_run = new_next_run;
230                                                 return;
231                                         }
232
233                                         if (!timer.disposed) {
234                                                 // We should only change next_run after removing and before adding
235                                                 timer.next_run = new_next_run;
236                                                 Add (timer);
237                                                 // If this timer is next in line, wake up the scheduler
238                                                 wake = (list.GetByIndex (0) == timer);
239                                         }
240                                 }
241                                 if (wake)
242                                         changed.Set ();
243                         }
244
245                         // lock held by caller
246                         int FindByDueTime (long nr)
247                         {
248                                 int min = 0;
249                                 int max = list.Count - 1;
250                                 if (max < 0)
251                                         return -1;
252
253                                 if (max < 20) {
254                                         while (min <= max) {
255                                                 Timer t = (Timer) list.GetByIndex (min);
256                                                 if (t.next_run == nr)
257                                                         return min;
258                                                 if (t.next_run > nr)
259                                                         return -1;
260                                                 min++;
261                                         }
262                                         return -1;
263                                 }
264
265                                 while (min <= max) {
266                                         int half = min + ((max - min) >> 1);
267                                         Timer t = (Timer) list.GetByIndex (half);
268                                         if (nr == t.next_run)
269                                                 return half;
270                                         if (nr > t.next_run)
271                                                 min = half + 1;
272                                         else
273                                                 max = half - 1;
274                                 }
275
276                                 return -1;
277                         }
278
279                         // This should be the only caller to list.Add!
280                         void Add (Timer timer)
281                         {
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);
285                                 if (idx != -1) {
286                                         bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
287                                         while (true) {
288                                                 idx++;
289                                                 if (up)
290                                                         timer.next_run++;
291                                                 else
292                                                         timer.next_run--;
293
294                                                 if (idx >= list.Count)
295                                                         break;
296                                                 Timer t2 = (Timer) list.GetByIndex (idx);
297                                                 if (t2.next_run != timer.next_run)
298                                                         break;
299                                         }
300                                 }
301                                 list.Add (timer, timer);
302                                 //PrintList ();
303                         }
304
305                         int InternalRemove (Timer timer)
306                         {
307                                 int idx = list.IndexOfKey (timer);
308                                 if (idx >= 0)
309                                         list.RemoveAt (idx);
310                                 return idx;
311                         }
312
313                         static WaitCallback TimerCaller = new WaitCallback (TimerCB);
314                         static void TimerCB (object o)
315                         {
316                                 Timer timer = (Timer) o;
317                                 try {
318                                         timer.callback (timer.state);
319                                 } catch {}
320                         }
321
322                         void SchedulerThread ()
323                         {
324                                 Thread.CurrentThread.Name = "Timer-Scheduler";
325                                 ArrayList new_time = new ArrayList (512);
326                                 while (true) {
327                                         int ms_wait = -1;
328                                         long ticks = DateTime.GetTimeMonotonic ();
329                                         lock (this) {
330                                                 changed.Reset ();
331                                                 //PrintList ();
332                                                 int i;
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)
337                                                                 break;
338
339                                                         list.RemoveAt (i);
340                                                         count--;
341                                                         i--;
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));
346                                                         if (no_more) {
347                                                                 timer.next_run = Int64.MaxValue;
348                                                         } else {
349                                                                 timer.next_run = DateTime.GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
350                                                                 new_time.Add (timer);
351                                                         }
352                                                 }
353
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];
358                                                         Add (timer);
359                                                 }
360                                                 new_time.Clear ();
361                                                 ShrinkIfNeeded (new_time, 512);
362
363                                                 // Shrink the list
364                                                 int capacity = list.Capacity;
365                                                 count = list.Count;
366                                                 if (capacity > 1024 && count > 0 && (capacity / count) > 3)
367                                                         list.Capacity = count * 2;
368
369                                                 long min_next_run = Int64.MaxValue;
370                                                 if (list.Count > 0)
371                                                         min_next_run = ((Timer) list.GetByIndex (0)).next_run;
372
373                                                 //PrintList ();
374                                                 ms_wait = -1;
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;
379                                                         else {
380                                                                 ms_wait = (int)(diff);
381                                                                 if (ms_wait < 0)
382                                                                         ms_wait = 0;
383                                                         }
384                                                 }
385                                         }
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);
388                                 }
389                         }
390
391                         void ShrinkIfNeeded (ArrayList list, int initial)
392                         {
393                                 int capacity = list.Capacity;
394                                 int count = list.Count;
395                                 if (capacity > initial && count > 0 && (capacity / count) > 3)
396                                         list.Capacity = count * 2;
397                         }
398
399                         /*
400                         void PrintList ()
401                         {
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);
406                                 }
407                                 Console.WriteLine ("END----");
408                         }
409                         */
410                 }
411         }
412 }
413