public async Task Kick() { var interval = TimeSpan.FromSeconds(1); var stopwatch = Stopwatch.StartNew(); var watchdog = new WatchdogTimer(() => stopwatch.Stop()) { Interval = interval }; const int count = 4; const int delay = 500; for (var i = 0; i < count; i++) { watchdog.Kick(); // kick start. await Task.Delay(delay); } Assert.True(watchdog.IsEnabled); // ReSharper disable once ArrangeRedundantParentheses Assert.True(stopwatch.ElapsedMilliseconds <= (count * delay) + 200); // ReSharper disable once ArrangeRedundantParentheses Assert.True(stopwatch.ElapsedMilliseconds >= (count * delay) - 200); }
public void ResetTest() { using (WatchdogTimer uut = new WatchdogTimer(3000, "ResetTest")) { bool resetCalled = false; Exception err = new Exception("My Exception"); uut.OnTimeoutExpired += delegate() { resetCalled = true; }; uut.Start(); // Calling Reset every half second should // prevent the watchdog from firing, which is set to // expire after 3 seconds. for (int i = 0; i < 12; ++i) { uut.Reset(); Thread.Sleep(500); } uut.Stop(); Assert.IsFalse(resetCalled); } }
public LockWindow() { this.ShowMaxRestoreButton = false; this.ShowMinButton = false; this.IgnoreTaskbarOnMaximize = true; this.ShowCloseButton = false; this.ShowTitleBar = false; this.WindowState = System.Windows.WindowState.Maximized; this.WindowStyle = System.Windows.WindowStyle.None; this.ResizeMode = System.Windows.ResizeMode.NoResize; this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; this._isClosing = false; this.SourceInitialized += SourceInitializedEventHandler; this.Closing += ClosingEventHandler; this.Closed += ClosedEventHandler; _viewModel = new ViewModels.LockWindow(); this.DataContext = _viewModel; InputManager.Current.PreProcessInput += GlobalClickEventHandler; InitializeComponent(); _emergencyTimer = new WatchdogTimer(30 * 1000, Emergency_Start); _emergencyTimer.Start(); _timeUpdateTimer = new DispatcherTimer(); _timeUpdateTimer.Interval = new TimeSpan(0, 0, 30); _timeUpdateTimer.IsEnabled = true; _timeUpdateTimer.Tick += TimeUpdateTimer_Tick;; _timeUpdateTimer.Start(); }
public void ExceptionThrownEvent() { using (WatchdogTimer uut = new WatchdogTimer(500, "ExceptionThrownEvent")) { ManualResetEvent resetEvent = new ManualResetEvent(false); Exception err = new Exception("My Exception"); uut.OnTimeoutExpired += delegate() { throw err; }; Exception foundException = null; uut.OnTimeoutExpiredError += delegate(Exception e) { foundException = e; resetEvent.Set(); }; uut.Start(); Assert.IsTrue(resetEvent.WaitOne(3000)); Assert.AreSame(err, foundException); } }
public void StopEvent() { using (WatchdogTimer uut = new WatchdogTimer(500, "StopEvent")) { AutoResetEvent resetEvent = new AutoResetEvent(false); uut.OnTimeoutExpired += delegate() { resetEvent.Set(); // By forcing Stop() to be called on itself, we can guarentee that // we won't hit a racecondition anywhere, as we are stopping it on the timer thread. uut.Stop(); }; uut.Start(); Assert.IsTrue(resetEvent.WaitOne(2000)); Assert.IsFalse(resetEvent.WaitOne(3000)); uut.Start(); Assert.IsTrue(resetEvent.WaitOne(2000)); Assert.IsFalse(resetEvent.WaitOne(3000)); } }
public void InvalidOperationTests() { WatchdogTimer uut = new WatchdogTimer(int.MaxValue, "InvalidOperationTests"); bool started = false; bool stopped = false; bool reset = false; uut.OnStarted += () => { started = true; }; uut.OnStopped += () => { stopped = true; }; uut.OnReset += () => { reset = true; }; Assert.Throws <InvalidOperationException>(() => uut.Stop()); // Can't stop if its not started. Assert.Throws <InvalidOperationException>(() => uut.Reset()); // Ensure events didn't fire. Assert.IsFalse(started); Assert.IsFalse(stopped); Assert.IsFalse(reset); // Call Start uut.Start(); Assert.IsTrue(started); started = false; // Calling start again should get an InvalidOperationException Assert.Throws <InvalidOperationException>(() => uut.Start()); Assert.IsFalse(started); Assert.IsFalse(stopped); Assert.IsFalse(reset); uut.Reset(); Assert.IsFalse(started); Assert.IsFalse(stopped); Assert.IsTrue(reset); reset = false; uut.Stop(); Assert.IsFalse(started); Assert.IsTrue(stopped); Assert.IsFalse(reset); stopped = false; uut.Dispose(); // Should get ObjectDisposedExceptions Assert.Throws <ObjectDisposedException>(() => uut.Start()); Assert.Throws <ObjectDisposedException>(() => uut.Stop()); Assert.Throws <ObjectDisposedException>(() => uut.Reset()); Assert.IsFalse(started); Assert.IsFalse(stopped); Assert.IsFalse(reset); // Nothing bad should happen if we call Dispose again uut.Dispose(); }
public void Properties() { var interval = TimeSpan.FromMinutes(5); var watchdog = new WatchdogTimer(() => { }) { Interval = interval }; Assert.Equal(interval, watchdog.Interval); }
public void Properties() { var interval = TimeSpan.FromMinutes(5); const bool isEnabled = true; var watchdog = new WatchdogTimer(() => { /* do nothing */ }) { Interval = interval, IsEnabled = isEnabled }; Assert.Equal(interval, watchdog.Interval); Assert.Equal(isEnabled, watchdog.IsEnabled); }
/// <summary> /// Releases the managed and unmanaged resources used by the <see cref="Connection"/>. /// </summary> /// <param name="disposing">A value indicating whether the object is in the process of disposing.</param> protected virtual void Dispose(bool disposing) { if (!Disposed) { if (disposing) { Disconnect("Connection is being disposed", new ObjectDisposedException(GetType().Name)); InactivityTimer?.Dispose(); WatchdogTimer?.Dispose(); Stream?.Dispose(); TcpClient?.Dispose(); } Disposed = true; } }
/// <summary> /// Disconnects the client. /// </summary> /// <param name="message">The optional message or reason for the disconnect.</param> /// <param name="exception">The optional Exception associated with the disconnect.</param> public void Disconnect(string message = null, Exception exception = null) { if (State != ConnectionState.Disconnected && State != ConnectionState.Disconnecting) { message = message ?? exception?.Message; ChangeState(ConnectionState.Disconnecting, message); InactivityTimer?.Stop(); WatchdogTimer?.Stop(); Stream?.Close(); TcpClient?.Close(); ChangeState(ConnectionState.Disconnected, message, exception); } }
public async Task Timeout() { var interval = TimeSpan.FromSeconds(1); var stopwatch = Stopwatch.StartNew(); // ReSharper disable once UnusedVariable var watchdog = new WatchdogTimer(() => stopwatch.Stop()) { Interval = interval }; await Task.Delay(2000); Assert.True(stopwatch.ElapsedMilliseconds <= interval.TotalMilliseconds + 200); Assert.True(stopwatch.ElapsedMilliseconds >= interval.TotalMilliseconds - 200); }
public void TimeoutEvent() { using (WatchdogTimer uut = new WatchdogTimer(1000, "TimeoutEvent")) { AutoResetEvent resetEvent = new AutoResetEvent(false); uut.OnTimeoutExpired += delegate() { resetEvent.Set(); }; uut.Start(); Assert.IsTrue(resetEvent.WaitOne(5000)); Assert.IsTrue(resetEvent.WaitOne(5000)); Assert.IsTrue(resetEvent.WaitOne(5000)); } }
public void WriteDoubleWord(long offset, uint value) { lock (localLock) { switch ((Register)offset) { case Register.ControlRegister: if (value == 0x1) { WatchdogTimer.ResetValue(); } break; case Register.PeriodIntervalModeRegister: PeriodIntervalTimer.Limit = value; PeriodIntervalTimer.Enable(); break; case Register.InterruptDisableRegister: this.Log(LogLevel.Noisy, "Disabling interrupt 0x{0:X}", value); interruptMaskRegister &= ~value; break; case Register.InterruptEnableRegister: this.Log(LogLevel.Noisy, "Enabling interrupt 0x{0:X}", value); interruptMaskRegister |= value; break; case Register.RealTimeModeRegister: RealTimeTimer.Divider = (int)value; break; default: this.LogUnhandledWrite(offset, value); return; } } }
/// <summary> /// Asynchronously connects the client to the configured <see cref="IPEndPoint"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A Task representing the asynchronous operation.</returns> /// <exception cref="InvalidOperationException"> /// Thrown when the connection is already connected, or is transitioning between states. /// </exception> /// <exception cref="TimeoutException"> /// Thrown when the time attempting to connect exceeds the configured <see cref="ConnectionOptions.ConnectTimeout"/> value. /// </exception> /// <exception cref="OperationCanceledException"> /// Thrown when <paramref name="cancellationToken"/> cancellation is requested. /// </exception> /// <exception cref="ConnectionException">Thrown when an unexpected error occurs.</exception> public async Task ConnectAsync(CancellationToken?cancellationToken = null) { if (State != ConnectionState.Pending && State != ConnectionState.Disconnected) { throw new InvalidOperationException($"Invalid attempt to connect a connected or transitioning connection (current state: {State})"); } cancellationToken = cancellationToken ?? CancellationToken.None; // create a new TCS to serve as the trigger which will throw when the CTS times out a TCS is basically a 'fake' task // that ends when the result is set programmatically. create another for cancellation via the externally provided token. var timeoutTaskCompletionSource = new TaskCompletionSource <bool>(); var cancellationTaskCompletionSource = new TaskCompletionSource <bool>(); try { ChangeState(ConnectionState.Connecting, $"Connecting to {IPEndPoint}"); // create a new CTS with our desired timeout. when the timeout expires, the cancellation will fire using (var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(Options.ConnectTimeout))) { var connectTask = TcpClient.ConnectAsync(IPEndPoint.Address, IPEndPoint.Port); // register the TCS with the CTS. when the cancellation fires (due to timeout), it will set the value of the // TCS via the registered delegate, ending the 'fake' task, then bind the externally supplied CT with the same // TCS. either the timeout or the external token can now cancel the operation. using (timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true))) using (((CancellationToken)cancellationToken).Register(() => cancellationTaskCompletionSource.TrySetResult(true))) { var completedTask = await Task.WhenAny(connectTask, timeoutTaskCompletionSource.Task, cancellationTaskCompletionSource.Task).ConfigureAwait(false); if (completedTask == timeoutTaskCompletionSource.Task) { throw new TimeoutException($"Operation timed out after {Options.ConnectTimeout} milliseconds"); } else if (completedTask == cancellationTaskCompletionSource.Task) { throw new OperationCanceledException("Operation cancelled"); } if (connectTask.Exception?.InnerException != null) { throw connectTask.Exception.InnerException; } } } InactivityTimer?.Start(); WatchdogTimer.Start(); Stream = TcpClient.GetStream(); ChangeState(ConnectionState.Connected, $"Connected to {IPEndPoint}"); } catch (Exception ex) { Disconnect($"Connection Error: {ex.Message}", ex); if (ex is TimeoutException || ex is OperationCanceledException) { throw; } throw new ConnectionException($"Failed to connect to {IPEndPoint}: {ex.Message}", ex); } }
private void CreateTimers() { _screenSaverTimer = new WatchdogTimer(1 * 60 * 1000, ScreenSaver_Start); _screenSaverTimer.Start(); }
public void StartDisposeTest() { WatchdogTimer uut = new WatchdogTimer(1000, "StartDisposeTest"); uut.Dispose(); }