generated from gemstone/gemtem
-
Notifications
You must be signed in to change notification settings - Fork 1
/
PrecisionTimer.cs
612 lines (523 loc) · 21.5 KB
/
PrecisionTimer.cs
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//******************************************************************************************************
// PrecisionTimer.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 11/22/2003 - Leslie Sanford
// Original version of source code for Multimedia.Timer class.
// 04/10/2008 - James Brock
// Original version of source code for DateTimePrecise class.
// 08/21/2008 - J. Ritchie Carroll
// Integrated, merged and adapted for general use as PrecisionTimer.
// 09/14/2009 - Stephen C. Wills
// Added new header and license agreement.
// 11/02/2009 - J. Ritchie Carroll
// Added SetMinimumTimerResolution and ClearMinimumTimerResolution to control
// system level minimum timer resolutions.
// 09/22/2011 - J. Ritchie Carroll
// Added Mono implementation exception regions.
// 12/14/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
#region [ Contributor License Agreements ]
/**********************************************************************************\
PrecisionTimer class
Copyright © 2009 - J. Ritchie Carroll for combined work
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
Multimedia.Timer class:
Copyright (c) 2006 Leslie Sanford
* 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.
* Leslie Sanford
* Email: jabberdabber@hotmail.com
\**********************************************************************************/
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Timers;
using Gemstone.EventHandlerExtensions;
namespace Gemstone;
/// <summary>
/// Represents information about the system's multimedia timer capabilities.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct TimerCapabilities
{
/// <summary>Minimum supported period in milliseconds.</summary>
public int PeriodMinimum;
/// <summary>Maximum supported period in milliseconds.</summary>
public int PeriodMaximum;
}
/// <summary>
/// Represents an exception that is thrown when a <see cref="PrecisionTimer"/> fails to start.
/// </summary>
[Serializable]
public class TimerStartException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="TimerStartException"/> class.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public TimerStartException(string message)
: base(message)
{
}
}
/// <summary>
/// Represents a high-resolution timer and timestamp class.
/// </summary>
/// <remarks>
/// For Windows deployments, implementation is based on the Windows multimedia timer. For other
/// deployments, e.g., POSIX, implementation uses a basic timer for compatibility - this should
/// have ~10ms of resolution when used on standard Linux systems.
/// </remarks>
// Future deployments may want to consider an implementation that uses OS specific timers:
// For Windows use of multimedia style implementation below should be sufficient.
// For Linux see http://www.ittc.ku.edu/utime/ as an example.
public class PrecisionTimer : IDisposable
{
#region [ Members ]
// Defines constants for the multimedia Timer's event types.
private enum TimerMode
{
OneShot, // Timer event occurs once.
Periodic // Timer event occurs periodically.
}
// Represents the method that is called by Windows when a timer event occurs.
private delegate void TimerProc(int id, int msg, int user, int param1, int param2);
/// <summary>
/// Occurs when the <see cref="PrecisionTimer"/> has started.
/// </summary>
public event EventHandler? Started;
/// <summary>
/// Occurs when the <see cref="PrecisionTimer"/> has stopped.
/// </summary>
public event EventHandler? Stopped;
/// <summary>
/// </summary>
public event EventHandler? Tick;
// Fields
private readonly Timer m_timer; // For now, basic timer implementation for POSIX deployments
private int m_timerID; // Timer identifier.
private readonly TimerProc m_timeProc; // Called by Windows when a timer periodic event occurs.
private TimerMode m_mode; // Timer mode.
private int m_period; // Period between timer events in milliseconds.
private int m_resolution; // Timer resolution in milliseconds.
private bool m_running; // Indicates whether or not the timer is running.
private bool m_disposed; // Indicates whether or not the timer has been disposed.
private EventArgs? m_eventArgs; // Private user event args to pass into Ticks call
#endregion
#region [ Constructors ]
/// <summary>
/// Initializes a new instance of the <see cref="PrecisionTimer"/> class.
/// </summary>
public PrecisionTimer()
{
// Initialize timer with default values.
m_mode = TimerMode.Periodic;
m_running = false;
if (Common.IsPosixEnvironment)
{
m_timeProc = default!;
m_timer = new Timer();
m_timer.Elapsed += m_timer_Elapsed;
m_period = 10;
m_resolution = 10;
}
else
{
m_timer = default!;
m_timeProc = TimerEventCallback;
m_period = Capabilities.PeriodMinimum;
m_resolution = 1;
}
}
/// <summary>
/// Releases the unmanaged resources before the <see cref="PrecisionTimer"/> object is reclaimed by <see cref="GC"/>.
/// </summary>
~PrecisionTimer()
{
Dispose(false);
}
#endregion
#region [ Properties ]
/// <summary>
/// Gets or sets the time between <see cref="Tick"/> events, in milliseconds.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// If the timer has already been disposed.
/// </exception>
public int Period
{
get
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
return m_period;
}
set
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
if (value < Capabilities.PeriodMinimum || value > Capabilities.PeriodMaximum)
throw new ArgumentOutOfRangeException(nameof(value), value, "Multimedia Timer period out of range");
m_period = value;
if (IsRunning && m_mode == TimerMode.Periodic)
{
Stop();
Start(m_eventArgs);
}
}
}
/// <summary>
/// Gets or sets the <see cref="PrecisionTimer"/> resolution, in milliseconds.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// If the timer has already been disposed.
/// </exception>
/// <remarks>
/// <para>
/// The resolution is in milliseconds. The resolution increases with smaller values;
/// a resolution of 0 indicates periodic events should occur with the greatest possible
/// accuracy. To reduce system overhead, however, you should use the maximum value
/// appropriate for your application.
/// </para>
/// <para>
/// This property is currently ignored under Mono deployments.
/// </para>
/// </remarks>
public int Resolution
{
get
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
return m_resolution;
}
set
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "Multimedia timer resolution out of range");
m_resolution = value;
if (IsRunning && m_mode == TimerMode.Periodic)
{
Stop();
Start(m_eventArgs);
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="PrecisionTimer"/> should raise the
/// <see cref="Tick"/> event each time the specified period elapses or only after the first
/// time it elapses.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>
/// <c>true</c>true if the <see cref="PrecisionTimer"/> should raise the <see cref="Ticks"/>
/// event each time the interval elapses; <c>false</c> if it should raise the event only once
/// after the first time the interval elapses. The default is <c>true</c>.
/// </returns>
public bool AutoReset
{
get
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
return m_mode == TimerMode.Periodic;
}
set
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
m_mode = value ? TimerMode.Periodic : TimerMode.OneShot;
if (IsRunning && m_mode == TimerMode.Periodic)
{
Stop();
Start(m_eventArgs);
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="PrecisionTimer"/> is running.
/// </summary>
public bool IsRunning => m_running;
/// <summary>
/// Gets <see cref="System.EventArgs"/> specified in <see cref="Start(System.EventArgs)"/> used to pass into <see cref="Tick"/> event.
/// </summary>
public EventArgs? EventArgs => m_eventArgs;
#endregion
#region [ Methods ]
/// <summary>
/// Releases all the resources used by the <see cref="PrecisionTimer"/> object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="PrecisionTimer"/> object and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (m_disposed)
return;
try
{
if (!disposing)
return;
if (IsRunning)
Stop();
m_timer.Dispose();
}
finally
{
m_disposed = true; // Prevent duplicate dispose.
}
}
/// <summary>
/// Starts the <see cref="PrecisionTimer"/>.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// The timer has already been disposed.
/// </exception>
/// <exception cref="TimerStartException">
/// The timer failed to start.
/// </exception>
public void Start()
{
Start(EventArgs.Empty);
}
/// <summary>
/// Starts the <see cref="PrecisionTimer"/> with the specified <see cref="EventArgs"/>.
/// </summary>
/// <param name="userArgs">User defined event arguments to pass into raised <see cref="Ticks"/> event.</param>
/// <exception cref="ObjectDisposedException">
/// The timer has already been disposed.
/// </exception>
/// <exception cref="TimerStartException">
/// The timer failed to start.
/// </exception>
public void Start(EventArgs? userArgs)
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
if (m_running)
return;
// Cache user event args to pass into Ticks parameter
m_eventArgs = userArgs;
// Create and start timer.
if (Common.IsPosixEnvironment)
{
try
{
m_timer.Interval = m_period;
m_timer.AutoReset = m_mode == TimerMode.Periodic;
m_timer.Start();
m_running = true;
Started?.SafeInvoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
throw new TimerStartException("Unable to start precision timer: " + ex.Message);
}
}
else
{
m_timerID = timeSetEvent(m_period, m_resolution, m_timeProc, IntPtr.Zero, m_mode);
// If the timer was created successfully.
if (m_timerID != 0)
{
m_running = true;
Started?.SafeInvoke(this, EventArgs.Empty);
}
else
{
throw new TimerStartException("Unable to start precision timer");
}
}
}
/// <summary>
/// Stops <see cref="PrecisionTimer"/>.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// If the timer has already been disposed.
/// </exception>
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")]
public void Stop()
{
if (m_disposed)
throw new ObjectDisposedException("PrecisionTimer");
if (!m_running)
return;
// Stop and destroy timer.
if (Common.IsPosixEnvironment)
{
m_timer.Stop();
}
else
{
timeKillEvent(m_timerID);
m_timerID = 0;
}
m_running = false;
Stopped?.SafeInvoke(this, EventArgs.Empty);
}
private void m_timer_Elapsed(object? sender, ElapsedEventArgs e) =>
Tick?.SafeInvoke(this, m_eventArgs ?? EventArgs.Empty);
// Callback method called by the Win32 multimedia timer when a timer event occurs.
private void TimerEventCallback(int id, int msg, int user, int param1, int param2)
{
Tick?.SafeInvoke(this, m_eventArgs ?? EventArgs.Empty);
if (m_mode == TimerMode.OneShot)
Stop();
}
#endregion
#region [ Static ]
// Static Fields
private static readonly TimerCapabilities s_capabilities; // Multimedia timer capabilities.
// Static Constructor
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")]
static PrecisionTimer()
{
if (Common.IsPosixEnvironment)
{
s_capabilities.PeriodMinimum = 1;
s_capabilities.PeriodMaximum = int.MaxValue;
}
else
{
// Get multimedia timer capabilities
timeGetDevCaps(ref s_capabilities, Marshal.SizeOf(s_capabilities));
}
}
// Static Properties
/// <summary>
/// Gets the system multimedia timer capabilities.
/// </summary>
public static TimerCapabilities Capabilities => s_capabilities;
// Static Methods
/// <summary>
/// Requests a minimum resolution for periodic timers such as the <see cref="PrecisionTimer"/>.
/// </summary>
/// <param name="period">
/// Minimum timer resolution, in milliseconds, for the application. A lower value specifies a higher (more accurate) resolution.
/// </param>
/// <remarks>
/// <para>
/// Call this function immediately before using the <see cref="PrecisionTimer"/> and call <see cref="ClearMinimumTimerResolution"/>
/// immediately after you are finished using the PrecisionTimer. You must match each call to <see cref="SetMinimumTimerResolution"/>
/// with a call to ClearMinimumTimerResolution specifying the same minimum resolution <paramref name="period"/> in both calls.
/// An application can make multiple ClearMinimumTimerResolution calls as long as each call is matched with a call to ClearMinimumTimerResolution.
/// This function affects a global Windows setting. Windows uses the lowest value (that is, highest resolution) requested by any process.
/// Setting a higher resolution can improve the accuracy of time-out intervals in wait functions. However, it can also reduce overall system
/// performance, because the thread scheduler switches tasks more often. High resolutions can also prevent the CPU power management system from
/// entering power-saving modes. See timeBeginPeriod Windows API for more information.
/// </para>
/// <para>
/// This method is currently ignored under Mono deployments.
/// </para>
/// </remarks>
public static void SetMinimumTimerResolution(int period)
{
if (Common.IsPosixEnvironment)
return;
if (timeBeginPeriod(period) != 0)
throw new InvalidOperationException("Specified period resolution is out of range and is not supported.");
}
/// <summary>
/// Clears a previously set minimum timer resolution established using <see cref="SetMinimumTimerResolution"/>.
/// </summary>
/// <param name="period">
/// Minimum timer resolution specified in the previous call to the <see cref="SetMinimumTimerResolution"/> function.
/// </param>
/// <remarks>
/// <para>
/// Call this function immediately after you are finished using the <see cref="PrecisionTimer"/>. You must match each call to
/// <see cref="SetMinimumTimerResolution"/> with a call to <see cref="ClearMinimumTimerResolution"/>, specifying the same minimum
/// resolution <paramref name="period"/> in both calls. An application can make multiple SetMinimumTimerResolution calls as long
/// as each call is matched with a call to ClearMinimumTimerResolution.
/// </para>
/// <para>
/// This method is currently ignored under Mono deployments.
/// </para>
/// </remarks>
public static void ClearMinimumTimerResolution(int period)
{
if (Common.IsPosixEnvironment)
return;
if (timeEndPeriod(period) != 0)
throw new InvalidOperationException("Specified period resolution is out of range and is not supported.");
}
// Gets timer capabilities.
[DllImport("winmm.dll")]
private static extern int timeGetDevCaps(ref TimerCapabilities caps, int sizeOfTimerCaps);
// Creates and starts the timer.
[DllImport("winmm.dll")]
private static extern int timeSetEvent(int delay, int resolution, TimerProc proc, IntPtr user, TimerMode mode);
// Stops and destroys the timer.
[DllImport("winmm.dll")]
private static extern int timeKillEvent(int id);
// Sets the minimum resolution for periodic timers.
[DllImport("winmm.dll")]
private static extern int timeBeginPeriod(int period);
// Clears a previously set minimum timer resolution.
[DllImport("winmm.dll")]
private static extern int timeEndPeriod(int period);
#endregion
}