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