Given a input text file containing the Urls, I would like to download the corresponding files all at once. I use the answer to this question UserState using WebClient and TaskAsync download from Async CTP as reference.
public void Run()
{
List<string> urls = File.ReadAllLines(@"c:/temp/Input/input.txt").ToList();
int index = 0;
Task[] tasks = new Task[urls.Count()];
foreach (string url in urls)
{
WebClient wc = new WebClient();
string path = string.Format("{0}image-{1}.jpg", @"c:/temp/Output/", index+1);
Task downloadTask = wc.DownloadFileTaskAsync(new Uri(url), path);
Task outputTask = downloadTask.ContinueWith(t => Output(path));
tasks[index] = outputTask;
}
Console.WriteLine("Start now");
Task.WhenAll(tasks);
Console.WriteLine("Done");
}
public void Output(string path)
{
Console.WriteLine(path);
}
I expected that the downloading of the files would begin at the point of "Task.WhenAll(tasks)". But it turns out that the output look likes
c:/temp/Output/image-2.jpg c:/temp/Output/image-1.jpg c:/temp/Output/image-4.jpg c:/temp/Output/image-6.jpg c:/temp/Output/image-3.jpg [many lines deleted] Start now c:/temp/Output/image-18.jpg c:/temp/Output/image-19.jpg c:/temp/Output/image-20.jpg c:/temp/Output/image-21.jpg c:/temp/Output/image-23.jpg [many lines deleted] Done
Why does the downloading begin before WaitAll is called? What can I change to achieve what I would like (i.e. all tasks will begin at the same time)?
Thanks