Asynchronous File Download with Progress Bar

后端 未结 4 1610
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 03:18

I am attempting to have a progress bar\'s progress change as the WebClient download progress changes. This code still downloads the file yet when I call s

4条回答
  •  失恋的感觉
    2020-11-29 04:19

    UI Thread will be freezed when you click startDownload(). If you don't want get form freezed, you use startDownload() in another thread and make progress updating in cross-threaded. One way,

    private void startDownload()
    {
        Thread thread = new Thread(() => {
              WebClient client = new WebClient();
              client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
              client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
              client.DownloadFileAsync(new Uri("http://joshua-ferrara.com/luahelper/lua.syn"), @"C:\LUAHelper\Syntax Files\lua.syn");
        });
        thread.Start();
    }
    void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        this.BeginInvoke((MethodInvoker) delegate {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;
            label2.Text = "Downloaded " + e.BytesReceived + " of " + e.TotalBytesToReceive;
            progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
        });
    }
    void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        this.BeginInvoke((MethodInvoker) delegate {
             label2.Text = "Completed";
        }); 
    }
    

    Read more multi-threading in Google like this http://msdn.microsoft.com/en-us/library/ms951089.aspx

    -Fixed missing close ); to the bgThread declaration

提交回复
热议问题