SCCManager/Remontor/Pinger/PingTask.cs

93 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace Remontor.Pinger
{
internal class PingTask
{
private string NameOrAddress;
private int TimeoutCount;
private IPAddress Ip;
private IComp Comp;
private Panel panel;
private Ping pinger;
public PingTask( IComp comp)
{
this.Comp = comp;
this.NameOrAddress = comp.GetNetName();
pinger = new Ping();
pinger.PingCompleted += Pinger_PingCompleted;
try
{
pinger.SendPingAsync(NameOrAddress, 3);
}
catch
{
pinger.SendAsyncCancel();
}
}
public PingTask(Panel panel, IComp comp)
{
this.panel = panel;
this.Comp = comp;
this.NameOrAddress = comp.GetNetName();
pinger = new Ping();
pinger.PingCompleted += Pinger_PingCompleted;
try
{
pinger.SendPingAsync(NameOrAddress,3);
}
catch
{
pinger.SendAsyncCancel();
if (panel != null) panel.BackColor = Color.OrangeRed;
}
}
private void Pinger_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Reply == null)
{
if (panel != null) panel.BackColor = Color.OrangeRed;
return;
}
bool pingable;
bool succes;
long ping;
pingable = e.Reply.Status == IPStatus.TimedOut;
succes = e.Reply.Status == IPStatus.Success;
ping = e.Reply.RoundtripTime;
Ip = e.Reply.Address;
if (!succes)
{
if (panel != null) panel.BackColor = Color.OrangeRed;
TimeoutCount++;
}
else
{
if (panel != null) panel.BackColor = Color.Lime;
Comp.SetIP(Ip);
}
PingResult pingResult = new PingResult(ping, TimeoutCount, Ip, pingable, succes, NameOrAddress);
PingManager.WriteResult(pingResult);
this.pinger.Dispose();
//throw new NotImplementedException();
}
}
}