Home
Map
Ping: System.Net.NetworkInformation (async, await)Use the Ping and PingReply classes in System.Net.NetworkInformation. The async and await keywords are used.
C#
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.
Detail We create an instance of Ping using its constructor. No argument is needed.
Detail We invoke SendPingAsync on the Ping class. We receive a PingReply object. We must use "await" here.
async
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.
A short summary. With System.Net.NetworkInformation, we can send pings. Async and await can be used to handle multiple tasks at once.
C#VB.NETPythonGoJavaSwiftRust
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.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.