简体   繁体   中英

Adding Task to Tasklist in ForLoop

I need to send a request to multiple servers and am trying to use tasks to run each connection asynchronously. I have a function that is configured to make the connections:

 internal static Task<EventRecordEx> GetEventRecordFromServer(string server, string activityID)

I have tried the following but it runs synchronously...

var taskList = new List<Task<EventRecordEx>>();
foreach (string server in server_list)
{
    taskList.Add(GetEventRecordFromServer(server, id));
}
await Task.Factory.ContinueWhenAll(taskList.ToArray(), completedTasks =>
{
    foreach (var task in completedTasks)
    {  
        // do something with the results
    }
});

What am I doing wrong?

In my understanding when you use .ContinueWhenAll, you'll have a hard time debugging for the exceptions when one of the tasks fail as it will return an AggregateException, I'd suggest running the task individually, then use .ConfigureAwait(false) to make sure that it runs in a nun UI thread like so:

foreach(Task task in taskList.ToArray()){

    await task.ConfigureAwait(false);

    // Do something.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM