簡體   English   中英

如何從“第三方”庫中的方法返回另一個值?

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

例如,我可以創建類(具有兩個公共屬性,一個用於任務,第二個用於url)並返回實例。 但是我將此方法與其他方法聯系在一起。

您對此問題有解決方案嗎?

如果您希望能夠將任務與創建任務的網址相關聯,則可以使用字典進行映射:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM