开发者

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(开发者_JAVA技巧);

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜