File: Timer.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (464 lines) | stat: -rw-r--r-- 11,852 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//
// System.Threading.Timer.cs
//
// Authors:
// 	Dick Porter (dick@ximian.com)
// 	Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2001, 2002 Ximian, Inc.  http://www.ximian.com
// Copyright (C) 2004-2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;


namespace System.Threading
{
#if WASM
	internal static class WasmRuntime {
		static Dictionary<int, Action> callbacks;
		static int next_id;

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		static extern void SetTimeout (int timeout, int id);

		internal static void ScheduleTimeout (int timeout, Action action) {
			if (callbacks == null)
				callbacks = new Dictionary<int, Action> ();
			int id = ++next_id;
			callbacks [id] = action;
			SetTimeout (timeout, id);
		}

		//XXX Keep this in sync with mini-wasm.c:mono_set_timeout_exec
		static void TimeoutCallback (int id) {
			var cb = callbacks [id];
			callbacks.Remove (id);
			cb ();
		}
	}
#endif


	[ComVisible (true)]
	public sealed class Timer
		: MarshalByRefObject, IDisposable, IAsyncDisposable
	{
		static Scheduler scheduler => Scheduler.Instance;
#region Timer instance fields
		TimerCallback callback;
		object state;
		long due_time_ms;
		long period_ms;
		long next_run; // in ticks. Only 'Scheduler' can change it except for new timers without due time.
		bool disposed;
		bool is_dead, is_added;
#endregion
		public Timer (TimerCallback callback, object state, int dueTime, int period)
		{
			Init (callback, state, dueTime, period);
		}

		public Timer (TimerCallback callback, object state, long dueTime, long period)
		{
			Init (callback, state, dueTime, period);
		}

		public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
		{
			Init (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
		}

		[CLSCompliant(false)]
		public Timer (TimerCallback callback, object state, uint dueTime, uint period)
		{
			// convert all values to long - with a special case for -1 / 0xffffffff
			long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
			long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
			Init (callback, state, d, p);
		}

		public Timer (TimerCallback callback)
		{
			Init (callback, this, Timeout.Infinite, Timeout.Infinite);
		}

		void Init (TimerCallback callback, object state, long dueTime, long period)
		{
			if (callback == null)
				throw new ArgumentNullException ("callback");
			
			this.callback = callback;
			this.state = state;
			this.is_dead = false;
			this.is_added = false;

			Change (dueTime, period, true);
		}

		public bool Change (int dueTime, int period)
		{
			return Change (dueTime, period, false);
		}

		public bool Change (TimeSpan dueTime, TimeSpan period)
		{
			return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds, false);
		}

		[CLSCompliant(false)]
		public bool Change (uint dueTime, uint period)
		{
			// convert all values to long - with a special case for -1 / 0xffffffff
			long d = (dueTime == UInt32.MaxValue) ? Timeout.Infinite : (long) dueTime;
			long p = (period == UInt32.MaxValue) ? Timeout.Infinite : (long) period;
			return Change (d, p, false);
		}

		public void Dispose ()
		{
			if (disposed)
				return;

			disposed = true;
			scheduler.Remove (this);
		}

		public bool Change (long dueTime, long period)
		{
			return Change (dueTime, period, false);
		}

		const long MaxValue = UInt32.MaxValue - 1;

		bool Change (long dueTime, long period, bool first)
		{
			if (dueTime > MaxValue)
				throw new ArgumentOutOfRangeException ("dueTime", "Due time too large");

			if (period > MaxValue)
				throw new ArgumentOutOfRangeException ("period", "Period too large");

			// Timeout.Infinite == -1, so this accept everything greater than -1
			if (dueTime < Timeout.Infinite)
				throw new ArgumentOutOfRangeException ("dueTime");

			if (period < Timeout.Infinite)
				throw new ArgumentOutOfRangeException ("period");

			if (disposed)
				throw new ObjectDisposedException (null, Environment.GetResourceString ("ObjectDisposed_Generic"));

			due_time_ms = dueTime;
			period_ms = period;
			long nr;
			if (dueTime == 0) {
				nr = 0; // Due now
			} else if (dueTime < 0) { // Infinite == -1
				nr = long.MaxValue;
				/* No need to call Change () */
				if (first) {
					next_run = nr;
					return true;
				}
			} else {
				nr = dueTime * TimeSpan.TicksPerMillisecond + GetTimeMonotonic ();
			}

			scheduler.Change (this, nr);
			return true;
		}

		public bool Dispose (WaitHandle notifyObject)
		{
			if (notifyObject == null)
				throw new ArgumentNullException ("notifyObject");
			Dispose ();
			NativeEventCalls.SetEvent (notifyObject.SafeWaitHandle);
			return true;
		}

		public ValueTask DisposeAsync ()
		{
			Dispose ();
			return new ValueTask (Task.FromResult<object> (null));
		}

		// extracted from ../../../../external/referencesource/mscorlib/system/threading/timer.cs
		internal void KeepRootedWhileScheduled()
		{
		}

		// TODO: Environment.TickCount should be enough as is everywhere else
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		static extern long GetTimeMonotonic ();

		struct TimerComparer : IComparer, IComparer<Timer> {
			int IComparer.Compare (object x, object y)
			{
				if (x == y)
					return 0;
				Timer tx = (x as Timer);
				if (tx == null)
					return -1;
				Timer ty = (y as Timer);
				if (ty == null)
					return 1;
				return Compare(tx, ty);
			}

			public int Compare (Timer tx, Timer ty)
			{
				long result = tx.next_run - ty.next_run;
				return (int)Math.Sign(result);
			}
		}

		sealed class Scheduler {
			static readonly Scheduler instance = new Scheduler ();
			
			volatile bool needReSort = true;
			List<Timer> list;
			long current_next_run = Int64.MaxValue;

#if WASM
			bool scheduled_zero;

			void InitScheduler () {
			}

			void WakeupScheduler () {
				if (!scheduled_zero) {
					WasmRuntime.ScheduleTimeout (0, this.RunScheduler);
					scheduled_zero = true;
				}
			}

			void RunScheduler() {
				scheduled_zero = false;
				int ms_wait = RunSchedulerLoop ();
				if (ms_wait >= 0) {
					WasmRuntime.ScheduleTimeout (ms_wait, this.RunScheduler);
					if (ms_wait == 0)
						scheduled_zero = true;
				}
			}
#else
			ManualResetEvent changed;

			void InitScheduler () {
				changed = new ManualResetEvent (false);
				Thread thread = new Thread (SchedulerThread);
				thread.IsBackground = true;
				thread.Start ();
			}

			void WakeupScheduler () {
				changed.Set ();
			}

			void SchedulerThread ()
			{
				Thread.CurrentThread.Name = "Timer-Scheduler";
				while (true) {
					int ms_wait = -1;
					lock (this) {
						changed.Reset ();
						ms_wait = RunSchedulerLoop ();
					}
					// Wait until due time or a timer is changed and moves from/to the first place in the list.
					changed.WaitOne (ms_wait);
				}
			}

#endif
			public static Scheduler Instance {
				get { return instance; }
			}

			private Scheduler ()
			{
				list = new List<Timer> (1024);
				InitScheduler ();
			}

			public void Remove (Timer timer)
			{
				lock (this) {
					// If this is the next item due (index = 0), the scheduler will wake up and find nothing.
					// No need to Pulse ()
					InternalRemove (timer);
				}
			}

			public void Change (Timer timer, long new_next_run)
			{
				if (timer.is_dead)
					timer.is_dead = false;

				bool wake = false;
				lock (this) {
					needReSort = true;

					if (!timer.is_added) {
						timer.next_run = new_next_run;
						Add(timer);
						wake = current_next_run > new_next_run;
					} else {
						if (new_next_run == Int64.MaxValue) {
							timer.next_run = new_next_run;
							InternalRemove (timer);
							return;
						}

						if (!timer.disposed) {
							// We should only change next_run after removing and before adding
							timer.next_run = new_next_run;
							// FIXME
							wake = current_next_run > new_next_run;
						}
					}
				}
				if (wake)
					WakeupScheduler();
			}

			// This should be the only caller to list.Add!
			void Add (Timer timer)
			{
				timer.is_added = true;
				needReSort = true;
				list.Add (timer);
				if (list.Count == 1)
					WakeupScheduler();
				//PrintList ();
			}

			void InternalRemove (Timer timer)
			{
				timer.is_dead = true;
				needReSort = true;
			}

			static void TimerCB (object o)
			{
				Timer timer = (Timer) o;
				timer.callback (timer.state);
			}

			void FireTimer (Timer timer) {
				long period = timer.period_ms;
				long due_time = timer.due_time_ms;
				bool no_more = (period == -1 || ((period == 0 || period == Timeout.Infinite) && due_time != Timeout.Infinite));
				if (no_more) {
					timer.next_run = Int64.MaxValue;
					timer.is_dead = true;
				} else {
					timer.next_run = GetTimeMonotonic () + TimeSpan.TicksPerMillisecond * timer.period_ms;
					timer.is_dead = false;
				}
				ThreadPool.UnsafeQueueUserWorkItem (TimerCB, timer);
			}

			int RunSchedulerLoop () {
				int ms_wait = -1;
				int i;
				long ticks = GetTimeMonotonic ();
				var comparer = new TimerComparer();

				if (needReSort) {
					list.Sort(comparer);
					needReSort = false;
				}

				long min_next_run = Int64.MaxValue;

				for (i = 0; i < list.Count; i++) {
					Timer timer = list[i];
					if (timer.is_dead)
						continue;

					if (timer.next_run <= ticks) {
						FireTimer(timer);
					}

					min_next_run = Math.Min(min_next_run, timer.next_run);

					if ((timer.next_run > ticks) && (timer.next_run < Int64.MaxValue))
						timer.is_dead = false;
				}

				for (i = 0; i < list.Count; i++) {
					Timer timer = list[i];
					if (!timer.is_dead)
						continue;
					
					timer.is_added = false;
					needReSort = true;
					list[i] = list[list.Count - 1];
					i--;
					list.RemoveAt(list.Count - 1);

					if (list.Count == 0)
						break;
				}

				if (needReSort) {
					list.Sort(comparer);
					needReSort = false;
				}

				//PrintList ();
				ms_wait = -1;
				current_next_run = min_next_run;
				if (min_next_run != Int64.MaxValue) {
					long diff = (min_next_run - GetTimeMonotonic ())  / TimeSpan.TicksPerMillisecond;
					if (diff > Int32.MaxValue)
						ms_wait = Int32.MaxValue - 1;
					else {
						ms_wait = (int)(diff);
						if (ms_wait < 0)
							ms_wait = 0;
					}
				}
				return ms_wait;
			}

			/*
			void PrintList ()
			{
				Console.WriteLine ("BEGIN--");
				for (int i = 0; i < list.Count; i++) {
					Timer timer = (Timer) list.GetByIndex (i);
					Console.WriteLine ("{0}: {1}", i, timer.next_run);
				}
				Console.WriteLine ("END----");
			}
			*/
		}
	}
}