/
Timer.cs
323 lines (293 loc) · 10.6 KB
/
Timer.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Threading;
namespace System.Timers
{
/// <summary>
/// Handles recurring events in an application.
/// </summary>
[DefaultProperty("Interval"), DefaultEvent("Elapsed")]
public partial class Timer : Component, ISupportInitialize
{
private double _interval;
private bool _enabled;
private bool _initializing;
private bool _delayedEnable;
private ElapsedEventHandler? _onIntervalElapsed;
private bool _autoReset;
private ISynchronizeInvoke? _synchronizingObject;
private bool _disposed;
private Threading.Timer? _timer;
private readonly TimerCallback _callback;
private object? _cookie;
/// <summary>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.
/// </summary>
public Timer() : base()
{
_interval = 100;
_enabled = false;
_autoReset = true;
_initializing = false;
_delayedEnable = false;
_callback = new TimerCallback(MyTimerCallback);
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </summary>
/// <param name="interval">
/// The time, in milliseconds, between events. The value must be greater than zero and less than or equal to <see cref="int.MaxValue"/>.
/// </param>
public Timer(double interval) : this()
{
if (interval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
}
double roundedInterval = Math.Ceiling(interval);
if (roundedInterval > int.MaxValue || roundedInterval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
}
_interval = (int)roundedInterval;
}
/// <summary>
/// Initializes a new instance of the <see cref='Timer'/> class, setting the <see cref='Interval'/> property to the specified period.
/// </summary>
/// <param name="interval">
/// The time between events. The value in milliseconds must be greater than zero and less than or equal to <see cref="int.MaxValue"/>.
/// </param>
public Timer(TimeSpan interval) : this(interval.TotalMilliseconds)
{
}
/// <summary>
/// Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed, when Enabled is set to true.
/// </summary>
[TimersDescription(TimersDescriptionStringId.TimerAutoReset), DefaultValue(true)]
public bool AutoReset
{
get => _autoReset;
set
{
if (DesignMode)
{
_autoReset = value;
}
else if (_autoReset != value)
{
_autoReset = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able to raise events at a defined interval.
/// The default value by design is false, don't change it.
/// </summary>
[TimersDescription(TimersDescriptionStringId.TimerEnabled), DefaultValue(false)]
public bool Enabled
{
get => _enabled;
set
{
if (DesignMode)
{
_delayedEnable = value;
_enabled = value;
}
else if (_initializing)
{
_delayedEnable = value;
}
else if (_enabled != value)
{
if (!value)
{
if (_timer != null)
{
_cookie = null;
_timer.Dispose();
_timer = null;
}
_enabled = value;
}
else
{
_enabled = value;
if (_timer == null)
{
ObjectDisposedException.ThrowIf(_disposed, this);
int i = (int)Math.Ceiling(_interval);
_cookie = new object();
_timer = new Threading.Timer(_callback, _cookie, Timeout.Infinite, Timeout.Infinite);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
else
{
UpdateTimer();
}
}
}
}
}
private void UpdateTimer()
{
Debug.Assert(_timer != null, $"{nameof(_timer)} was expected not to be null");
int i = (int)Math.Ceiling(_interval);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
/// <summary>
/// Gets or sets the interval on which to raise events.
/// </summary>
[TimersDescription(TimersDescriptionStringId.TimerInterval), DefaultValue(100d)]
public double Interval
{
get => _interval;
set
{
if (value <= 0)
{
throw new ArgumentException(SR.Format(SR.TimerInvalidInterval, value, 0));
}
_interval = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
/// <summary>
/// Occurs when the <see cref='System.Timers.Timer.Interval'/> has
/// elapsed.
/// </summary>
[TimersDescription(TimersDescriptionStringId.TimerIntervalElapsed)]
public event ElapsedEventHandler Elapsed
{
add => _onIntervalElapsed += value;
remove => _onIntervalElapsed -= value;
}
/// <summary>
/// Sets the enable property in design mode to true by default.
/// </summary>
public override ISite? Site
{
get => base.Site;
set
{
base.Site = value;
if (DesignMode)
{
_enabled = true;
}
}
}
/// <summary>
/// Gets or sets the object used to marshal event-handler calls that are issued when
/// an interval has elapsed.
/// </summary>
[DefaultValue(null), TimersDescription(TimersDescriptionStringId.TimerSynchronizingObject)]
public ISynchronizeInvoke? SynchronizingObject
{
get
{
if (_synchronizingObject == null && DesignMode)
{
IDesignerHost? host = (IDesignerHost?)GetService(typeof(IDesignerHost));
object? baseComponent = host?.RootComponent;
if (baseComponent != null && baseComponent is ISynchronizeInvoke)
{
_synchronizingObject = (ISynchronizeInvoke)baseComponent;
}
}
return _synchronizingObject;
}
set => _synchronizingObject = value;
}
/// <summary>
/// Notifies the object that initialization is beginning and tells it to stand by.
/// </summary>
public void BeginInit()
{
Close();
_initializing = true;
}
/// <summary>
/// Disposes of the resources (other than memory) used by
/// the <see cref='System.Timers.Timer'/>.
/// </summary>
public void Close()
{
_initializing = false;
_delayedEnable = false;
_enabled = false;
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
}
protected override void Dispose(bool disposing)
{
Close();
_disposed = true;
base.Dispose(disposing);
}
/// <summary>
/// Notifies the object that initialization is complete.
/// </summary>
public void EndInit()
{
_initializing = false;
Enabled = _delayedEnable;
}
/// <summary>
/// Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.
/// </summary>
public void Start() => Enabled = true;
/// <summary>
/// Stops the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='false'/>.
/// </summary>
public void Stop()
{
Enabled = false;
}
private void MyTimerCallback(object? state)
{
// System.Threading.Timer will not cancel the work item queued before the timer is stopped.
// We don't want to handle the callback after a timer is stopped.
if (state != _cookie)
{
return;
}
if (!_autoReset)
{
_enabled = false;
}
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(DateTime.Now);
try
{
// To avoid race between remove handler and raising the event
ElapsedEventHandler? intervalElapsed = _onIntervalElapsed;
if (intervalElapsed != null)
{
if (SynchronizingObject != null && SynchronizingObject.InvokeRequired)
SynchronizingObject.BeginInvoke(intervalElapsed, new object[] { this, elapsedEventArgs });
else
intervalElapsed(this, elapsedEventArgs);
}
}
catch
{
}
}
}
}