view ServerMonitor/Objects/Checks/PingCheck.cs @ 14:2db36ab759de

Add comments.
author Brad Greco <brad@bgreco.net>
date Mon, 22 Apr 2019 21:10:42 -0400
parents 453ecc1ed9ea
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;
        }
    }
}