private void TaskCallback(CancellationToken token) { using (var ping = new Ping()) { while (!token.IsCancellationRequested) { var dateTime = DateTime.Now; PingReply reply = null; try { reply = ping.Send(Host, (int) Timeout.TotalMilliseconds); } catch (Exception ex) { if (!token.IsCancellationRequested) { var eventArgs = new PingExceptionEventArgs {Exception = ex}; OnPingException(eventArgs); if (eventArgs.Cancel) { return; } } else { return; } } if (reply != null) { var result = new PingResult { DateTime = dateTime, Status = reply.Status, TimeCost = reply.Status == IPStatus.TimedOut ? Timeout : TimeSpan.FromMilliseconds(reply.RoundtripTime) }; PingResults.Add(result); OnPintTick(new PingTickEventArgs {Result = result}); } while (!token.IsCancellationRequested) { var sleep = Interval - (DateTime.Now - dateTime); var max = TimeSpan.FromMilliseconds(10); if (sleep > max) { sleep = max; } if (sleep > TimeSpan.Zero) { Thread.Sleep(sleep); } else { break; } } } } }
protected virtual void OnPingException(PingExceptionEventArgs e) { EventHandler<PingExceptionEventArgs> handler = PingException; if (handler != null) handler(this, e); }