Search code examples
c#task-parallel-libraryparallel-extensions

How to return another value from method in "third party" lib?


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?


Solution

  • 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];
        });
    });