diff --git a/ICD.Common.Utils.Tests/Timers/SafeTimerTest.cs b/ICD.Common.Utils.Tests/Timers/SafeTimerTest.cs new file mode 100644 index 0000000..ce0894c --- /dev/null +++ b/ICD.Common.Utils.Tests/Timers/SafeTimerTest.cs @@ -0,0 +1,89 @@ +using ICD.Common.Utils.Timers; +using NUnit.Framework; + +namespace ICD.Common.Utils.Tests.Timers +{ + [TestFixture] + public sealed class SafeTimerTest + { + [Test] + public void DisposeTest() + { + bool called = false; + SafeTimer timer = SafeTimer.Stopped(() => called = true); + + // Crestron timer tends to execute the callback on stop. + timer.Dispose(); + Assert.IsFalse(called); + } + + [Test] + public void StoppedTest() + { + bool called = false; + SafeTimer timer = SafeTimer.Stopped(() => called = true); + + Assert.IsFalse(called); + + timer.Dispose(); + } + + [Test] + public void StopTest() + { + bool called = false; + SafeTimer timer = SafeTimer.Stopped(() => called = true); + timer.Reset(100); + timer.Stop(); + + ThreadingUtils.Sleep(200); + + Assert.IsFalse(called); + + timer.Dispose(); + } + + [Test] + public void TriggerTest() + { + bool called = false; + SafeTimer timer = SafeTimer.Stopped(() => called = true); + + timer.Trigger(); + + Assert.IsTrue(called); + + timer.Dispose(); + } + + [Test] + public void ResetTest() + { + int called = 0; + SafeTimer timer = SafeTimer.Stopped(() => called++); + + timer.Reset(10); + + ThreadingUtils.Sleep(50); + + Assert.AreEqual(1, called); + + timer.Dispose(); + } + + [Test] + public void ResetRepeatTest() + { + int called = 0; + SafeTimer timer = SafeTimer.Stopped(() => called++); + + timer.Reset(10, 10); + + ThreadingUtils.Sleep(50); + + Assert.AreEqual(4, called, 1); + + timer.Dispose(); + } + } +} diff --git a/ICD.Common.Utils/Timers/SafeTimer.cs b/ICD.Common.Utils/Timers/SafeTimer.cs index aac2320..c79b123 100644 --- a/ICD.Common.Utils/Timers/SafeTimer.cs +++ b/ICD.Common.Utils/Timers/SafeTimer.cs @@ -48,6 +48,9 @@ namespace ICD.Common.Utils.Timers /// public SafeTimer(Action callback, long dueTime, long repeatPeriod) { + if (callback == null) + throw new ArgumentNullException("callback"); + m_Callback = callback; #if SIMPLSHARP m_Timer = new CTimer(SafeCallback, null, dueTime, repeatPeriod); @@ -106,6 +109,7 @@ namespace ICD.Common.Utils.Timers m_Timer.Reset(); #else m_Timer.Change(0, m_RepeatPeriod); + m_Callback(); #endif }