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.
    });
});

I could, for example, create class (with two public property, one for task, and second for url) and return instance. But This method i connected with others methods.

Have you some solution for this issue?

svick
  • 214,528
  • 47
  • 357
  • 477
mike00
  • 448
  • 1
  • 6
  • 15
  • 1
    Why are you using `ContinueWhenAll()` and `Paralell.ForEach()`? Wouldn't `ContinueWith()` on each `Task` be better? – svick May 20 '12 at 11:35
  • See here: http://blogs.msdn.com/b/pfxteam/archive/2010/05/04/10007557.aspx – mike00 May 20 '12 at 11:42
  • 1
    That post doesn't explain *why* are you doing it this way. Why wouldn't `ContinueWith()` on each `Task` be suitable for you? – svick May 20 '12 at 12:07

1 Answers1

1

If you want to be able to associate your tasks with the url that created them you could use a dictionary to do the mapping:

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];
    });
});
RichardTowers
  • 4,394
  • 1
  • 23
  • 42
  • I think doing it think way is not a good idea in general (although it might work in this specific case). For example, some async method could return the same `Task` for multiple different inputs, which would break your code. – svick May 20 '12 at 12:10
  • Yes. Unless there's some concrete reason to do things this way, I'd agree with calling `ContinueWith()` on each `Task`. – RichardTowers May 20 '12 at 12:25
  • @RichardTowers Thanks, indeed such a thing I wanted. – mike00 May 20 '12 at 14:00