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