From 1b208c0afaf62bc5acd9ce164ab56596e14877da Mon Sep 17 00:00:00 2001 From: Dunestorm Date: Thu, 11 Apr 2019 21:21:05 +0100 Subject: [PATCH] Ping requests can now be started and stopped on demand. --- TimedShutdown/PingWidget.cs | 27 ++++++++++++++----- .../ViewModels/ShellRootViewModel.cs | 7 +++-- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/TimedShutdown/PingWidget.cs b/TimedShutdown/PingWidget.cs index f03c876..506e020 100644 --- a/TimedShutdown/PingWidget.cs +++ b/TimedShutdown/PingWidget.cs @@ -9,7 +9,7 @@ namespace TimedShutdown public class PingWidget { IPAddress _ipAddress = IPAddress.None; - public bool IsCancellationRequested { get; set; } = false; + public bool WidgetHasInitialized { get; private set; } = false; BackgroundWorker contPingBackgroundWorker = new BackgroundWorker(); @@ -17,8 +17,21 @@ namespace TimedShutdown { _ipAddress = ipAddress; + contPingBackgroundWorker.WorkerSupportsCancellation = true; contPingBackgroundWorker.DoWork += ContPingBackgroundWorkerDoWork; - contPingBackgroundWorker.RunWorkerAsync(); + + if (contPingBackgroundWorker.IsBusy == false) + { + contPingBackgroundWorker.RunWorkerAsync(); + } + + WidgetHasInitialized = true; + } + + public void StopCurrentPingRequest() + { + contPingBackgroundWorker.CancelAsync(); + Debug.WriteLine("Stopped ping request"); } /// @@ -30,20 +43,22 @@ namespace TimedShutdown private void ContPingBackgroundWorkerDoWork(object sender, DoWorkEventArgs e) { - while (IsCancellationRequested == false) + while (contPingBackgroundWorker.CancellationPending == false) { - Thread.Sleep(5000); - Ping pingSender = new Ping(); IPAddress address = _ipAddress; PingReply reply = pingSender.Send(address); if (reply.Status == IPStatus.Success) + { Debug.WriteLine("Ping Success!"); + } else { Debug.WriteLine(reply.Status); - } + } + + Thread.Sleep(3000); } } } diff --git a/TimedShutdown/ViewModels/ShellRootViewModel.cs b/TimedShutdown/ViewModels/ShellRootViewModel.cs index 1d5a775..7ffc821 100644 --- a/TimedShutdown/ViewModels/ShellRootViewModel.cs +++ b/TimedShutdown/ViewModels/ShellRootViewModel.cs @@ -92,12 +92,15 @@ namespace TimedShutdown.ViewModels if (value == true) { - pingWidget.IsCancellationRequested = false; + pingWidget.InitatePingRequest(IPAddress.Parse(RemoteShutdown)); } else { - pingWidget.IsCancellationRequested = true; + if (pingWidget.WidgetHasInitialized == true) + { + pingWidget.StopCurrentPingRequest(); + } } } }