【问题标题】:Updating Progress Bar in a Form from Downloading in a Class从课堂下载更新表单中的进度条
【发布时间】:2013-02-07 07:51:37
【问题描述】:

我知道这里有很多问题,但我已经解决了很多问题并且运气不佳。我是事件和后台工作人员的新手,我只是不知道实现这一点的最佳方法。

我有一个 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;
}

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

【问题讨论】:

  • 以什么方式搞砸了?错误,没有反应好,...?

标签: c# winforms asynchronous progress-bar


【解决方案1】:

我有这个女巫和你想做的差不多,而且效果很好 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;
        }

【讨论】:

    【解决方案2】:

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

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

    问候

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 2014-01-12
      相关资源
      最近更新 更多