Files
TimedShutdown/TimedShutdown/PingWidget.cs

66 lines
1.9 KiB
C#

using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
namespace TimedShutdown
{
public class PingWidget
{
IPAddress _ipAddress = IPAddress.None;
public bool WidgetHasInitialized { get; private set; } = false;
BackgroundWorker contPingBackgroundWorker = new BackgroundWorker();
public void InitatePingRequest(IPAddress ipAddress)
{
_ipAddress = ipAddress;
contPingBackgroundWorker.WorkerSupportsCancellation = true;
contPingBackgroundWorker.DoWork += ContPingBackgroundWorkerDoWork;
if (contPingBackgroundWorker.IsBusy == false)
{
contPingBackgroundWorker.RunWorkerAsync();
}
WidgetHasInitialized = true;
}
public void StopCurrentPingRequest()
{
contPingBackgroundWorker.CancelAsync();
Debug.WriteLine("Stopped ping request");
}
/// <summary>
/// Will continuously ping the input IP address every 5 seconds,
/// will stop if a cancellation request is made.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ContPingBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
while (contPingBackgroundWorker.CancellationPending == false)
{
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);
}
}
}
}