view ServerMonitor/Objects/Checks/PingCheck.cs @ 2:453ecc1ed9ea

Disk space check
author Brad Greco <brad@bgreco.net>
date Sun, 06 Jan 2019 20:49:08 -0500
parents ServerMonitor/Objects/PingCheck.cs@3e1a2131f897
children 68d7834dc28e
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServerMonitorApp
{
    [DisplayName("Ping check"), Description("Check if the server responds to a ping request"), DisplayWeight(0)]
    public class PingCheck : Check
    {
        protected async override Task<CheckResult> ExecuteCheckAsync(CancellationToken token)
        {
            using (Ping ping = new Ping())
            {
                try
                {
                    PingReply reply = await ping.SendPingAsync(Server.Host, Timeout);
                    if (reply.Status == IPStatus.Success)
                        return Pass(string.Format("Reply received in {0} ms", reply.RoundtripTime));
                    else
                        return Fail("Ping result: " + reply.Status);
                }
                catch (PingException e)
                {
                    return Fail(e);
                }
            }

            // Cancellable version that doesn't actulaly work
            // might be useful as a TaskCompletionSource example though
            //
            //TaskCompletionSource<CheckResult> tcs = new TaskCompletionSource<CheckResult
            //
            //using (Ping ping = new Ping())
            //{
            //    token.Register(ping.SendAsyncCancel);
            //    ping.PingCompleted += (sender, e) =>
            //    {
            //        if (e.Error != null)
            //            tcs.SetResult(Fail("Ping failed: " + e.Error.GetBaseException().Message));
            //        else if (e.Reply.Status != IPStatus.Success)
            //            tcs.SetResult(Fail("Ping failed: " + e.Reply.Status.ToString()));
            //        else
            //            tcs.SetResult(Pass("Ping completed in " + e.Reply.RoundtripTime + "ms"));
            //    };
            //    ping.SendAsync(Server.Host, Timeout, null);
            //}

            //return tcs.Task;
        }
    }
}