Simple Console Application for checking if one of the hosts is available. The implementation should be for around 5 hosts to check with different response times and the method should return fast when one Host can be pinged. Is the asynchronous implementation O.K.?
using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
namespace PingMe
{
class Program
{
private static volatile bool _result;
private readonly CancellationTokenSource _source;
private readonly ParallelOptions _parallelOptions;
private readonly string[] _hostsToPing = {"google.com", "reddit.com", "netflix.com"};
private Program()
{
_source = new CancellationTokenSource();
var token = _source.Token;
_parallelOptions = new ParallelOptions
{
CancellationToken = token
};
}
private bool IsOneOfTheHostsAvailable()
{
try
{
Parallel.ForEach(_hostsToPing, _parallelOptions, (host) =>
{
try
{
var ping = new Ping();
var reply = ping.Send(host);
_parallelOptions.CancellationToken.ThrowIfCancellationRequested();
if (reply?.Status == IPStatus.Success)
{
_result = true;
Console.WriteLine($"Pinged {host}");
if (!_source.IsCancellationRequested)
_source.Cancel();
}
}
catch (Exception)
{
// we are only interested if one of the pings is successful, we don't care about the reason
}
});
}
catch (OperationCanceledException)
{
// we are done
}
return _result;
}
private static void Main()
{
var program = new Program();
var oneOfTheHostsIsAvailable = program.IsOneOfTheHostsAvailable();
Console.WriteLine($"One of the hosts is available: {oneOfTheHostsIsAvailable}");
}
}
}