Capturing results from multiple async tasks

72 Views Asked by At

For a project I needed a program which checks IP's for a response:

class Program
{
    public static int rcount = 0;
    public static int count = 0;

    static void Main(string[] args)
    {
        List<string> results = new List<string>();
        Console.BufferHeight = Int16.MaxValue - 1;
        Console.Write("addr3 or all: ");
        try
        {
            int addrin = int.Parse(Console.ReadLine());
            Check(addrin);
        }
        catch 
        {
            Parallel.For(0, 100, i =>
            {
                Check(i);
            });
            Console.WriteLine("0 - 100 complete");
            Console.ReadLine();
            Parallel.For(101, 200, i =>
            {
                Check(i);
            });
            Console.WriteLine("101 - 200 complete");
            Console.ReadLine();
            Parallel.For(201, 255, i =>
            {
                Check(i);
            });
            Console.WriteLine("201 - 255 complete");
            Console.ReadLine();
        }
        Console.ReadLine();
    }

    public static async Task Check(int addr3)
    {
        int icount = 0;
        for (int i = 1; i <= 255; i++)
        {
            count++;
            icount++;
            string ip = "192.168." + addr3 +"." + i;
            Ping ping = new Ping();
            PingReply reply = ping.Send(ip);
            if (reply.Status == IPStatus.Success)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(count + "   " + rcount + "   " + ip +
                    " is reachable." + "   " + icount + "/255");
                Console.ForegroundColor = ConsoleColor.Gray;
                rcount++;
            }
            else
            {
                Console.WriteLine(count + "   " + rcount + "   " + ip +
                    " is not reachable." + "   " + icount + "/255");
            }   
        }
    }
}

Now, because of the limited line maximum of a console (int16 - 1), I would want to capture all responding IP's.

I tried writing to a global array from each instance of the task, which didn't work and using return, which also doesn't work. I guess I could use await in the main method but this would be way to slow to wait for 65025 checks to complete one by one.

So how can I get the responding IP's? (There might be a very simple answer which I just did not find but I only know the basics of C# and don't understand every approach I have read about)

0

There are 0 best solutions below