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 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 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 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 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)); } }
/// <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(); }