Pregunta

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

Podría, por ejemplo, crear clases (con dos propiedades públicas, una para tarea, y la segunda para la URL) y la instancia de devolución.Pero este método que conecto con otros métodos.

¿Tienes alguna solución para este problema?

¿Fue útil?

Solución

Si desea poder asociar sus tareas con la URL que las creó, podría usar un diccionario para hacer el mapeo:

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top