1

Im trying to make a simple downloader, but i cant make it to update the GUI elements in my Form (Form1).

In the constructor for Form1 i call thread:

        Thread t = new Thread(new ThreadStart(fetch));
        t.Start();

And fetch looks something like this:

private void fetch()
{
        try
        {
            WebClient webClient = new WebClient();
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
            webClient.DownloadFile(updateurl, @"foo.iso");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.ToString());
        }
}

None of the events are triggered... altho, by looking at the foo.iso in the folder i see the file increase in size.

One of the events looks like this:

void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{   
    progressBar.Value = (int)(e.BytesReceived * 100 / e.TotalBytesToReceive);

    statusLabel.Text = "Downloading";
    descLabel.Text = progressBar.Value + " % complete";
}
Jason94
  • 13,320
  • 37
  • 106
  • 184
  • 1
    In general, don't explicitly start a thread, use a background thread from the thread pool. Do this with QueueUserWorkItem or some other call that relies on the pool. http://stackoverflow.com/questions/684640/advantage-of-using-thread-start-vs-queueuserworkitem – Cheeso Feb 17 '11 at 13:39

2 Answers2

2

I don't know, why they are not raised, but the problem is, that you are trying to update the UI from a non-UI thread.
How to do it, can be seen here: How to update the GUI from another thread in C#?

Community
  • 1
  • 1
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
2

You don't need to perform your fetch method in another thread, just use DownloadFileAsync instead of DownloadFile and it should work asynchronously.

Also, that's the reason why DownloadProgressChanged event doesn't trigger:

it works only with asynchronous calls (link).

digEmAll
  • 56,430
  • 9
  • 115
  • 140