L
L
littleguga2015-10-07 18:51:42
Programming
littleguga, 2015-10-07 18:51:42

How to properly organize multi-threaded/asynchronous downloads?

I download via WebClient. How will it be more correct and faster:
1 way:

spoiler
Task.Factory.StartNew(() =>
{
  myload(max_id);
}).ContinueWith((t) => {
  result.Text = "saved!";
  result.ForeColor = System.Drawing.Color.Green;

}, TaskScheduler.FromCurrentSynchronizationContext());

private void myload(int max_id)
{
  int i = 1;
  while(i <= max_id)
  {
    filename = path_tosave + "/" + i + ".png";
    loadurl = lurl + i + ".png";
    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += download_completed;
    webClient.DownloadFileAsync(new Uri(loadurl), filename);
    i++;
  }
}


Or separately for each file to create Task in a cycle?
Thanks in advance for your informative response!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dasha Tsiklauri, 2015-10-07
@littleguga

you break a lot of indices into parts, for example 1-100, 100-200, 200-300
in a cycle of 3 tasks you run

var tasks = new List<Task>();
for(var i=0;i<3;i++){
tasks.Add(Task.Run(()=>{
myload(from, till); // метод изменить, чтобы он индексы от и до принимал
}));
}
Task.WaitAll(tasks.ToArray());
// тут кусок кода после завершения всех

M
MonkAlex, 2015-10-31
@MonkAlex

I don't know about it right, but I use Parallel.ForEach quite successfully, creating WebClient instances internally.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question