How to develop an asynchronous mechanism to test pings?

Asked

Viewed 274 times

3

I have a problem of slowness in a transaction that usually performs pings to check 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 2 minutes. To decrease the total time of this transaction, I tried to implement asynchronous methods to test these IP’s simultaneously, but was unsuccessful. Below follows 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 (no 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?

1 answer

3

When you use "await" you are talking to Main Thread to synchronize with your async method, that is, it will wait for the result, resulting in the runtime equal to the previous one.

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.

  • Diego, could you post an example code using Task.Waitall(tasks)? In the meantime, I’ll try to implement as you indicated...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.