A ping can test whether a network location is responding. We can use ping to ensure (or monitor) the reliability of a network location (like a website).
With the Ping class
, found in the System.Net.NetworkInformation
namespace, we can send pings. We can use the async
and await
keywords to avoid blocking.
This example uses async
methods in System.Net.NetworkInformation
to send a ping. We begin by using Task to start and wait for the Test()
method.
SendPingAsync
on the Ping class
. We receive a PingReply
object. We must use "await
" here.using System; using System.Net.NetworkInformation; using System.Threading.Tasks; class Program { static void Main() { // Use Task class to start and wait for a Ping. Task task = new Task(Test); task.Start(); task.Wait(); // Done. Console.ReadLine(); } static async void Test() { // Create Ping instance. Ping ping = new Ping(); // Send a ping. PingReply reply = await ping.SendPingAsync("dotnetperls.com"); // Display the result. Console.WriteLine("ADDRESS:" + reply.Address.ToString()); Console.WriteLine("TIME:" + reply.RoundtripTime); } }ADDRESS:184.168.221.17 TIME:95
The Ping class
is ideal for monitoring whether a network location can be reached. It does not ensure anything beyond this.
async
and await
With the async
and await
keywords we have a more elegant way of handling async
methods. The Main
method can continue while Test()
is busy.
With System.Net.NetworkInformation
in the C# language, we can send pings. Async and await
can be used to handle multiple tasks at once.