简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM