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)并返回实例。但这种方法我与其他方法联系在一起。
你有解决这个问题的方法吗?
答案 0 :(得分:1)
如果您希望能够将您的任务与创建它们的网址相关联,您可以使用字典进行映射:
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];
});
});