0
Task<string>[] tableOfWebClientTasks = new Task<string>[taskCount];

for (int i = 0; i < taskCount; i++)
{
    tableOfWebClientTasks[i] = new WebClient().DownloadStringTask(allUrls[count - i - 1]);
}

Task.Factory.ContinueWhenAll(tableOfWebClientTasks, tasks =>
{
    Parallel.ForEach(tasks, task =>
    {
        //Here I have result from each task.
        //But information which url is executed on this task, is lost.
    });
});

例如,我可以创建类(具有两个公共属性,一个用于任务,第二个用于 url)并返回实例。但是这种方法我与其他方法联系在一起。

你有解决这个问题的办法吗?

4

1 回答 1

1

如果您希望能够将您的任务与创建它们的 url 相关联,您可以使用字典进行映射:

Task<string>[] tableOfWebClientTasks = new Task<string>[taskCount];
var taskIdToUrl = new Dictionary<int,string>();

for (int i = 0; i < taskCount; i++)
{
    var url = allUrls[count - i - 1];
    var task = new WebClient().DownloadStringTask(url);
    tableOfWebClientTasks[i] = task;
    taskIdToUrl.Add(task.Id, url);
}

TaskFactory.ContinueWhenAll(tableOfWebClientTasks, tasks =>
{
    Parallel.ForEach(tasks, task =>
    {
        // To get the url just do:
        var url = taskIdToUrl[task.Id];
    });
});
于 2012-05-20T11:54:00.137 回答