Loop asynchronous calls and process data at the end of all executions

3

I have a method of a web service that receives the IP of a server as a parameter and returns a DataSet . Multiple servers must be queried by this web service, A List<string> contains the list of IPs. A loop executes the method, a merge is returned to a local DataSet, and then a% winforms is populated with that data.

The code that does this is simple:

    foreach (var server in servers)
    {
        ds.Merge(ws.GetData(server));
    }

    dataGridView1.DataSource = ds.Tables[0];

This call runs in a queue and takes a while to finish, in addition to locking the entire form.

How can I convert this process to an asynchronous form using the DataGridView method with GetDataAsync and async to execute all calls at once and display the data in Task at the end?     

asked by anonymous 26.02.2014 / 15:57

1 answer

2

Do this:

var tasks = servers.Select(server => ws.GetDataAsync(server)).ToArray();
Task.WaitAll(tasks);
var results = tasks.SelectMany(t => t.Result).ToList();
foreach (var res in results)
    ds.Merge(res);

If the method in which the code exists (eg an event of a windows forms control) can be declared with async , it could still use await and leave execution of the whole block after await for when all results are ready:

private async Task EventoDoForm(EventArgs e)
{
    var tasks = servers.Select(server => ws.GetDataAsync(server)).ToArray();
    await Task.WhenAll(tasks);
    var results = tasks.SelectMany(t => t.Result).ToList();
    foreach (var res in results)
        ds.Merge(res);
}

So, the event will not crash form.

    
26.02.2014 / 16:11