Task.WaitAll卡住了

时间:2016-02-16 20:00:17

标签: c# task-parallel-library

我有一段看起来像这样的代码:

    var taskList = new Task<string>[masterResult.D.Count];
    for (int i = 0; i < masterResult.D.Count; i++)        //Go through all the lists we need to pull (based on master list) and create a task-list
    {
        using (var client = new WebClient())
        {
            Task<string> getDownloadsTask = client.DownloadStringTaskAsync(new Uri(agilityApiUrl + masterResult.D[i].ReferenceIdOfCollection + "?$format=json"));
            taskList[i] = getDownloadsTask;
        }
    }

    Task.WaitAll(taskList.Cast<Task>().ToArray());      //Wait for all results to come back

代码在Task.WaitAll之后冻结......我知道为什么,因为客户在呼叫时已经处理好了,是否可以延迟处理直到以后?你能推荐另一种方法吗?

2 个答案:

答案 0 :(得分:3)

您需要在任务中创建和部署WebClient。我没有办法测试这个,但看看你是否指向正确的方向:

    var taskList = new Task<string>[masterResult.D.Count];
    for (int i = 0; i < masterResult.D.Count; i++)        //Go through all the lists we need to pull (based on master list) and create a task-list
    {
        taskList[i] = Task.Run(() =>
        {
            using (var client = new WebClient())
            {
                return client.DownloadStringTaskAsync(new Uri(agilityApiUrl + masterResult.D[i].ReferenceIdOfCollection + "?$format=json"));

            }
        });
    }

    Task.WaitAll(taskList.Cast<Task>().ToArray());  

答案 1 :(得分:1)

我看不出代码是如何工作的,因为你在任务运行之前处理了WebClient

你想做这样的事情:

var taskList = new Task<string>[masterResult.D.Count];
for (int i = 0; i < masterResult.D.Count; i++)        //Go through all the lists we need to pull (based on master list) and create a task-list
{
    var client = new WebClient();
    Task<string> task = client.DownloadStringTaskAsync(new Uri(agilityApiUrl + masterResult.D[i].ReferenceIdOfCollection + "?$format=json"));
    task.ContinueWith(x => client.Dispose());
    taskList[i] = task;
}

Task.WaitAll(taskList.Cast<Task>().ToArray());      //Wait for all results to come back

即。如果在第一个循环中释放WebClient,则在使用Task.WaitAll触发任务时不会分配它。任务完成后将调用ContinueWith调用,因此可用于处理每个WebClient实例。

但是,要获取代码以执行对单个主机的并发请求,您需要配置服务点。阅读此问题:Trying to run multiple HTTP requests in parallel, but being limited by Windows (registry)