0f084b5fe39b832800f0395ae797878e161fe070
[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 #if MOONLIGHT
39                 : IDisposable
40 #else
41                 : MarshalByRefObject, IDisposable
42 #endif
43         {
44                 static readonly Scheduler scheduler = Scheduler.Instance;
45 #region Timer instance fields
46                 TimerCallback callback;
47                 object state;
48                 long due_time_ms;
49                 long period_ms;
50                 long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
51                 bool disposed;
52 #endregion
53                 public Timer (TimerCallback callback, object state, int dueTime, int period)
54                 {
55                         Init (callback, state, dueTime, period);
56                 }
57
58                 public Timer (TimerCallback callback, object state, long dueTime, long period)
59                 {
60                         Init (callback, state, dueTime, period);
61                 }
62
63                 public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
64                 {
65                         Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
66                 }
67
68                 [CLSCompliant(false)]
69                 public Timer (TimerCallback callback, object state, uint dueTime, uint period)
70                 {
71                         // convert all values to long - with a special case for -1 / 0xffffffff
72                         long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
73                         long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
74                         Init (callback, state, d, p);
75                 }
76
77                 public Timer (TimerCallback callback)
78                 {
79                         Init (callback, this, Timeout.Infinite, Timeout.Infinite);
80                 }
81
82                 void Init (TimerCallback callback, object state, long dueTime, long period)
83                 {
84                         if (callback == null)
85                                 throw new ArgumentNullException ("callback");
86                         
87                         this.callback = callback;
88                         this.state = state;
89
90                         Change (dueTime, period, true);
91                 }
92
93                 public bool Change (int dueTime, int period)
94                 {
95                         return Change (dueTime, period, false);
96                 }
97
98                 public bool Change (TimeSpan dueTime, TimeSpan period)
99                 {
100                         return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
101                 }
102
103                 [CLSCompliant(false)]
104                 public bool Change (uint dueTime, uint period)
105                 {
106                         // convert all values to long - with a special case for -1 / 0xffffffff
107                         long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
108                         long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
109                         return Change (d, p, false);
110                 }
111
112                 public void Dispose ()
113                 {
114                         if (disposed)
115                                 return;
116
117                         disposed = true;
118                         scheduler.Remove (this);
119                 }
120
121                 public bool Change (long dueTime, long period)
122                 {
123                         return Change (dueTime, period, false);
124                 }
125
126                 const long MaxValue = UInt32.MaxValue - 1;
127
128                 bool Change (long dueTime, long period, bool first)
129                 {
130                         if (dueTime > MaxValue)
131                                 throw new ArgumentOutOfRangeException ("dueTime", "Due time too large");
132
133                         if (period > MaxValue)
134                                 throw new ArgumentOutOfRangeException ("period", "Period too large");
135
136                         // Timeout.Infinite == -1, so this accept everything greater than -1
137                         if (dueTime < Timeout.Infinite)
138                                 throw new ArgumentOutOfRangeException ("dueTime");
139
140                         if (period < Timeout.Infinite)
141                                 throw new ArgumentOutOfRangeException ("period");
142
143                         if (disposed)
144                                 return false;
145
146                         due_time_ms = dueTime;
147                         period_ms = period;
148                         long nr;
149                         if (dueTime == 0) {
150                                 nr = 0; // Due now
151                         } else if (dueTime < 0) { // Infinite == -1
152                                 nr = long.MaxValue;
153                                 /* No need to call Change () */
154                                 if (first) {
155                                         next_run = nr;
156                                         return true;
157                                 }
158                         } else {
159                                 nr = dueTime * TimeSpan.TicksPerMillisecond + DateTime.GetTimeMonotonic ();
160                         }
161
162                         scheduler.Change (this, nr);
163                         return true;
164                 }
165
166                 public bool Dispose (WaitHandle notifyObject)
167                 {
168                         if (notifyObject == null)
169                                 throw new ArgumentNullException ("notifyObject");
170                         Dispose ();
171                         NativeEventCalls.SetEvent_internal (notifyObject.Handle);
172                         return true;
173                 }
174
175                 sealed class TimerComparer : IComparer {
176                         public int Compare (object x, object y)
177                         {
178                                 Timer tx = (x as Timer);
179                                 if (tx == null)
180                                         return -1;
181                                 Timer ty = (y as Timer);
182                                 if (ty == null)
183                                         return 1;
184                                 long result = tx.next_run - ty.next_run;
185                                 if (result == 0)
186                                         return x == y ? 0 : -1;
187                                 return result > 0 ? 1 : -1;
188                         }
189                 }
190
191                 sealed class Scheduler {
192                         static Scheduler instance;
193                         SortedList list;
194                         ManualResetEvent changed;
195
196                         static Scheduler ()
197                         {
198                                 instance = new Scheduler ();
199                         }
200
201                         public static Scheduler Instance {
202                                 get { return instance; }
203                         }
204
205                         private Scheduler ()
206                         {
207                                 changed = new ManualResetEvent (false);
208                                 list = new SortedList (new TimerComparer (), 1024);
209                                 Thread thread = new Thread (SchedulerThread);
210                                 thread.IsBackground = true;
211                                 thread.Start ();
212                         }
213
214                         public void Remove (Timer timer)
215                         {
216                                 // We do not keep brand new items or those with no due time.
217                                 if (timer.next_run == 0 || timer.next_run == Int64.MaxValue)
218                                         return;
219
220                                 lock (this) {
221                                         // If this is the next item due (index = 0), the scheduler will wake up and find nothing.
222                                         // No need to Pulse ()
223                                         InternalRemove (timer);
224                                 }
225                         }
226
227                         public void Change (Timer timer, long new_next_run)
228                         {
229                                 bool wake = false;
230                                 lock (this) {
231                                         InternalRemove (timer);
232                                         if (new_next_run == Int64.MaxValue) {
233                                                 timer.next_run = new_next_run;
234                                                 return;
235                                         }
236
237                                         if (!timer.disposed) {
238                                                 // We should only change next_run after removing and before adding
239                                                 timer.next_run = new_next_run;
240                                                 Add (timer);
241                                                 // If this timer is next in line, wake up the scheduler
242                                                 wake = (list.GetByIndex (0) == timer);
243                                         }
244                                 }
245                                 if (wake)
246                                         changed.Set ();
247                         }
248
249                         // lock held by caller
250                         int FindByDueTime (long nr)
251                         {
252                                 int min = 0;
253                                 int max = list.Count - 1;
254                                 if (max < 0)
255                                         return -1;
256
257                                 if (max < 20) {
258                                         while (min <= max) {
259                                                 Timer t = (Timer) list.GetByIndex (min);
260                                                 if (t.next_run == nr)
261                                                         return min;
262                                                 if (t.next_run > nr)
263                                                         return -1;
264                                                 min++;
265                                         }
266                                         return -1;
267                                 }
268
269                                 while (min <= max) {
270                                         int half = min + ((max - min) >> 1);
271                                         Timer t = (Timer) list.GetByIndex (half);
272                                         if (nr == t.next_run)
273                                                 return half;
274                                         if (nr > t.next_run)
275                                                 min = half + 1;
276                                         else
277                                                 max = half - 1;
278                                 }
279
280                                 return -1;
281                         }
282
283                         // This should be the only caller to list.Add!
284                         void Add (Timer timer)
285                         {
286                                 // Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
287                                 // Do not use list.IndexOfKey here. See bug #648130
288                                 int idx = FindByDueTime (timer.next_run);
289                                 if (idx != -1) {
290                                         bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
291                                         while (true) {
292                                                 idx++;
293                                                 if (up)
294                                                         timer.next_run++;
295                                                 else
296                                                         timer.next_run--;
297
298                                                 if (idx >= list.Count)
299                                                         break;
300                                                 Timer t2 = (Timer) list.GetByIndex (idx);
301                                                 if (t2.next_run != timer.next_run)
302                                                         break;
303                                         }
304                                 }
305                                 list.Add (timer, timer);
306                                 //PrintList ();
307                         }
308
309                         int InternalRemove (Timer timer)
310                         {
311                                 int idx = list.IndexOfKey (timer);
312                                 if (idx >= 0)
313                                         list.RemoveAt (idx);
314                                 return idx;
315                         }
316
317                         static WaitCallback TimerCaller = new WaitCallback (TimerCB);
318                         static void TimerCB (object o)
319                         {
320                                 Timer timer = (Timer) o;
321                                 try {
322                                         timer.callback (timer.state);
323                                 } catch {}
324                         }
325
326                         void SchedulerThread ()
327                         {
328                                 Thread.CurrentThread.Name = "Timer-Scheduler";
329                                 ArrayList new_time = new ArrayList (512);
330                                 while (true) {
331                                         int ms_wait = -1;
332                                         long ticks = DateTime.GetTimeMonotonic ();
333                                         lock (this) {
334                                                 changed.Reset ();
335                                                 //PrintList ();
336                                                 int i;
337                                                 int count = list.Count;
338                                                 for (i = 0; i < count; i++) {
339                                                         Timer timer = (Timer) list.GetByIndex (i);
340                                                         if (timer.next_run > ticks)
341                                                                 break;
342
343                                                         list.RemoveAt (i);
344                                                         count--;
345                                                         i--;
346 #if MOONLIGHT
347                                                         ThreadPool.QueueUserWorkItem (TimerCaller, timer);
348 #else
349                                                         ThreadPool.UnsafeQueueUserWorkItem (TimerCaller, timer);
350 #endif
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));
354                                                         if (no_more) {
355                                                                 timer.next_run = Int64.MaxValue;
356                                                         } else {
357                                                                 timer.next_run = DateTime.GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
358                                                                 new_time.Add (timer);
359                                                         }
360                                                 }
361
362                                                 // Reschedule timers with a new due time
363                                                 count = new_time.Count;
364                                                 for (i = 0; i < count; i++) {
365                                                         Timer timer = (Timer) new_time [i];
366                                                         Add (timer);
367                                                 }
368                                                 new_time.Clear ();
369                                                 ShrinkIfNeeded (new_time, 512);
370
371                                                 // Shrink the list
372                                                 int capacity = list.Capacity;
373                                                 count = list.Count;
374                                                 if (capacity > 1024 && count > 0 && (capacity / count) > 3)
375                                                         list.Capacity = count * 2;
376
377                                                 long min_next_run = Int64.MaxValue;
378                                                 if (list.Count > 0)
379                                                         min_next_run = ((Timer) list.GetByIndex (0)).next_run;
380
381                                                 //PrintList ();
382                                                 ms_wait = -1;
383                                                 if (min_next_run != Int64.MaxValue) {
384                                                         long diff = (min_next_run - DateTime.GetTimeMonotonic ())  / TimeSpan.TicksPerMillisecond;
385                                                         if (diff > Int32.MaxValue)
386                                                                 ms_wait = Int32.MaxValue - 1;
387                                                         else {
388                                                                 ms_wait = (int)(diff);
389                                                                 if (ms_wait < 0)
390                                                                         ms_wait = 0;
391                                                         }
392                                                 }
393                                         }
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);
396                                 }
397                         }
398
399                         void ShrinkIfNeeded (ArrayList list, int initial)
400                         {
401                                 int capacity = list.Capacity;
402                                 int count = list.Count;
403                                 if (capacity > initial && count > 0 && (capacity / count) > 3)
404                                         list.Capacity = count * 2;
405                         }
406
407                         /*
408                         void PrintList ()
409                         {
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);
414                                 }
415                                 Console.WriteLine ("END----");
416                         }
417                         */
418                 }
419         }
420 }
421