Ping. 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.
An example program. 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.
Start We create an instance of Ping using its constructor. No argument is needed.
Next We invoke SendPingAsync on the Ping class. We receive a PingReply object. We must use "await" here.
Result We get an Address if the network location was found. We also can record the time required to access the site.
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
Some notes. The Ping class is ideal for monitoring whether a network location can be reached. It does not ensure anything beyond this.
Notes, 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.
Summary. With System.Net.NetworkInformation in the C# language, we can send pings. Async and await can be used to handle multiple tasks at once.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 10, 2023 (text).