How to develop an asynchronous mechanism to test pings?

3

I'm having a slowness problem with a transaction that pings to see if certain IP's are accessible. It turns out that this transaction tests more than 20 different IP's, which makes the total transaction time is 2 minutes. To decrease the total time of this transaction, I tried to implement asynchronous methods to test these IPs simultaneously, but I did not succeed. Here is the code implemented so far.

    public async Task<List<Foo>> Testar(List<Foo> lista)
    {
        Task<Foo>[] teste = new Task<Foo>[lista.Count];
        for (int i = 0; i < lista.Count; i++)
        {
            teste[i] = Verificar(lista[i].IP);
        }

        for (int i = 0; i < lista.Count; i++)
        {
            lista[i].Status = await teste[i];
        }

        return lista;
    }

    public async Task<Status> Verificar(string ip)
    {
    int retorno = await TestarIP(ip);
    return ((Status)retorno); 
    }


    public async Task<int> TestarIP(string ip)
    {            
        if(new Ping().Send(ip, timeOutPing).Status.Equals(IPStatus.Success))
            return 1;
        else 
            return 2;
    }

The code runs as soon as the page loads (in onLoad), but even using Async / Await, is having the same runtime as before. So how can I create threads to test these ip's simultaneously?

    
asked by anonymous 27.08.2014 / 21:52

1 answer

3

When you use "await" you are talking to the Main Thread sync with your async method, ie it will wait for the result, resulting in the same runtime as before.

You need to create an array with tasks and use the Task.WaitAll (tasks) method, so they will run in parallel.

Note: Do not confuse async with parallel execution.

    
01.09.2014 / 21:54