从类中下载更新表单中的进度条

时间:2013-02-07 07:51:37

标签: c# winforms asynchronous progress-bar

我知道这里有很多问题,但我已经经历了很多问题而且运气不好。我是活动和背景工作者的新手,我只是不知道实现这一点的最佳方式。

我在C#中有一个基本的Windows窗体。它包含一个进度条。我正在调用一个下载文件的类。我希望进度条基于该下载进行更新。如果所有内容都在同一个类中,我可以正常工作,但我不能让它在这种情况下工作。处理这个问题的最佳方法是什么?我该如何处理它?目前我正在这样做:

WebClient downloader = new WebClient();             
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

然后,为了改变进度,我这样做:

public void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    pbDownload.Value = e.ProgressPercentage;
}

但是当我将所有这些除了进度条放在一个单独的类中之外,它会搞得一团糟。想法?谢谢!

2 个答案:

答案 0 :(得分:0)

我有这个女巫与你想要做的事情大致相同并且工作正常 FStatus ...表格参考

 FrmStatus FStatus = null;

        public void ProgressInit(String caption, string opis, int Max)
        {
            FStatus = new SZOKZZ.FrmStatus();
            FStatus.InitProc(Max);
            FStatus.SetCaption(caption, opis);
            FStatus.Show();
        }

        public void DLProgress(string curl, string cdl)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DLDone);
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DLSetProc);
            webClient.DownloadFileAsync(new Uri(curl), cdl);
        }
        private void DLSetProc(object sender, DownloadProgressChangedEventArgs e)
        {
            this._FileProcentDownloaded = e.ProgressPercentage;
            FStatus.SetProcDL(this._FileProcentDownloaded);

        }
        private void DLDone(object sender, AsyncCompletedEventArgs e)
        {
            _DlError = e.Error;
            FStatus.Dispose();
            FStatus = null;
        }

答案 1 :(得分:0)

你应该调用Application.DoEvents();强制您的表单根据新值更新控件:

   public void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            pbDownload.Value = e.ProgressPercentage;
            Application.DoEvents();
        }

此致