简体   繁体   English

将任务添加到ForLoop中的任务列表

[英]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: 以我的理解,当您使用.ContinueWhenAll时,如果其中一个任务失败,您将很难调试异常,因为它将返回AggregateException,我建议单独运行该任务,然后使用.ConfigureAwait(false)确保它在修女UI线程中运行,如下所示:

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

    await task.ConfigureAwait(false);

    // Do something.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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