Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / C#

Continuous asynchronous Ping using TAP and IProgress in C#5

Rate me:
Please Sign up or sign in to vote.
4.95/5 (23 votes)
15 Jan 2014CPOL4 min read 51.9K   3.2K   39  
This article shows how to use C# 5 async functions to create a continuous asynchronous ping and report progress to the UI.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Network;
using Ping = Network.Ping;

namespace PingConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            DoPing().Wait(); ;
            Console.WriteLine("All done");
            Console.Read();
        }

        private static async Task DoPing()
        {
            var Ips = Enumerable.Range(188, 2)
                .Select(nr => "192.168." + nr.ToString())
                .SelectMany(net => Enumerable.Range(0, 254).Select(nr => net + "." + nr.ToString()));

            var cts = new CancellationTokenSource();

            var tasks = Ips
                .Select(Network.Ping.ResolveAddress)
                .Select(ip => Ping.ContinuousPingAsync(ip, 500, 1000, new Progress<PingResult>(PrintResult), cts.Token));

            cts.CancelAfter(30000);

            await Task.WhenAll(tasks);
        }

        private static void PrintResult(PingResult result)
        {
            if (result.LastStatus == IPStatus.Success)
                Console.WriteLine("{0,-15}: ({1}/{2}) {3:fff}ms", result.Address, result.PingsSuccessfull, result.PingsTotal, result.AverageTime);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer evopro systems engineering AG
Germany Germany
Peter Butzhammer studied physics but decided to work as a software developer 10 years ago. He has a strong interest in statistics, simulation and functional programming.

Comments and Discussions