Jason94
Jason94

Reputation: 13620

Help with downloading with progressbar

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";
}

Upvotes: 1

Views: 244

Answers (2)

digEmAll
digEmAll

Reputation: 57230

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

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174477

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#?

Upvotes: 2

Related Questions