1

I am having trouble with with my image downloading program. When I run it, it freezes until all of the images are downloaded. The labels change but picturebox doesn't and I can't even move the program.

foreach (Match m in ms)
{
    label3.Text = m.Value;
    mastercount++;
    pictureBox1.ImageLocation = m.Value;
    try
    {
        WebClient wc = new WebClient();
        wc.DownloadFile(m.Value, @downloadDest + "\\"+ mastercount + ".jpeg");
        Thread.Sleep(1000);

    }
    catch (Exception x)
    {
        label3.Text = "Failed to download image" + m.Value;
    }
}
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
FJam
  • 736
  • 3
  • 13
  • 32
  • So you not only download one file after another, you also wait a second between each download. – Corak Jul 28 '13 at 17:51
  • 1
    Of course it waits, it's a blocking operation and you have just one thread. Try DownloadFileAsyncTask and working with continuations. – Benjamin Gruenbaum Jul 28 '13 at 17:52
  • with or without the thread it has the same problem. The only reason i put that was beacuse i was told it might help, but it didnt. – FJam Jul 28 '13 at 17:52

2 Answers2

7

The reason your application is freezing is because of these lines:

 wc.DownloadFile(m.Value, @downloadDest + "\\"+ mastercount + ".jpeg");
 Thread.Sleep(1000);

You are running this code on the Main Thread or UI Thread so no user interface operations can be performed while the above code is executing. In order to solve this you should look into threading. A good start would be the BackgroundWorker

See below:

See Also:

Community
  • 1
  • 1
jrbeverly
  • 1,611
  • 14
  • 20
0

If you don't need to do this as a Forms app, this will be a lot easier if you do it as a Console app. Console apps are generally easier to work without freezing and cross-thread access problems.

If you need to stick with a Forms app, the simplest solution is to replace Thread.Sleep with Application.DoEvents. It'll still freeze while downloading each image, and there are other issues that DoEvents can cause, but if you just need a quick fix, this is the easiest option.

Dax Fohl
  • 10,654
  • 6
  • 46
  • 90
  • you can't display the images in the console – FJam Jul 28 '13 at 18:06
  • @FJam okay wasn't sure that displaying was a requirement. Anyway the answer in my 2nd paragraph should still work for you in the Forms option. One line code change can get you what you need. – Dax Fohl Jul 28 '13 at 18:09