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?

3
  • 1
    Why are you using ContinueWhenAll() and Paralell.ForEach()? Wouldn't ContinueWith() on each Task be better? Commented May 20, 2012 at 11:35
  • See here: blogs.msdn.com/b/pfxteam/archive/2010/05/04/10007557.aspx Commented May 20, 2012 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? Commented May 20, 2012 at 12:07

1 Answer 1

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];
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Yes. Unless there's some concrete reason to do things this way, I'd agree with calling ContinueWith() on each Task.
@RichardTowers Thanks, indeed such a thing I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.