RaspberryIO/Unosquare.Swan.Lite/Components/TimerControl.cs
2019-12-04 17:10:06 +01:00

55 lines
1.9 KiB
C#

#if !NETSTANDARD1_3
using System;
using System.Threading;
using Unosquare.Swan.Abstractions;
namespace Unosquare.Swan.Components {
/// <summary>
/// Use this singleton to wait for a specific <c>TimeSpan</c> or time.
///
/// Internally this class will use a <c>Timer</c> and a <c>ManualResetEvent</c> to block until
/// the time condition is satisfied.
/// </summary>
/// <seealso cref="SingletonBase{TimerControl}" />
public class TimerControl : SingletonBase<TimerControl> {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Codequalität", "IDE0052:Ungelesene private Member entfernen", Justification = "<Ausstehend>")]
private readonly Timer _innerTimer;
private readonly IWaitEvent _delayLock = WaitEventFactory.Create(true);
/// <summary>
/// Initializes a new instance of the <see cref="TimerControl"/> class.
/// </summary>
protected TimerControl() => this._innerTimer = new Timer(
x => {
try {
this._delayLock.Complete();
this._delayLock.Begin();
} catch {
// ignore
}
},
null,
0,
15);
/// <summary>
/// Waits until the time is elapsed.
/// </summary>
/// <param name="untilDate">The until date.</param>
/// <param name="ct">The cancellation token.</param>
public void WaitUntil(DateTime untilDate, CancellationToken ct = default) {
while(!ct.IsCancellationRequested && DateTime.UtcNow < untilDate) {
this._delayLock.Wait();
}
}
/// <summary>
/// Waits the specified wait time.
/// </summary>
/// <param name="waitTime">The wait time.</param>
/// <param name="ct">The cancellation token.</param>
public void Wait(TimeSpan waitTime, CancellationToken ct = default) =>
this.WaitUntil(DateTime.UtcNow.Add(waitTime), ct);
}
}
#endif