c# - WPF 进度条未显示正确的进度

标签 c# wpf

我有一个应用程序,我要分块上传文件。我的前端是WPF,我有一个进度条来显示文件上传进度(上传是由单独的线程完成的,进度条是在上传开始时由子线程调用的单独形式)。

找到文件中的总 block 数来设置进度条的最大属性。

现在对于每个上传的 block ,我将进度条的值增加 1。

但令我惊讶的是,进度条开始递增但从未完成(它在几个 block 后停止显示进度)。

下面是负责上传文件的线程的代码:

 System.Threading.Thread thread = new Thread(
   new ThreadStart(
         delegate()
         {
              // show progress bar - Progress is the name of window containing progress bar
              Progress win = new Progress();
              win.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
              win.Show();

              // find number of blocks
             long BlockSize = 4096;
             FileInfo fileInf = new FileInfo(filename);
             long FileSize = fileInf.Length;
             long NumBlocks = FileSize / BlockSize;

             //set the min and max for progress bar
             win.Dispatcher.Invoke(
                  new Action(
                     delegate()
                     {
                            win.progressBar1.Minimum = 0;
                            win.progressBar1.Maximum = NumBlocks;                                                        
                     }
             ), System.Windows.Threading.DispatcherPriority.Render);

             //upload file
             while (true)
             {

                      // code to upload the file

                      win.Dispatcher.Invoke(
                          new Action(
                              delegate()
                              {
                                 win.progressBar1.Value += 1;
                              }
                      ), System.Windows.Threading.DispatcherPriority.Render);

             }
       }

谁能帮我分析一下为什么会这样。

谢谢。

最佳答案

问题是:

upload is done by separate thread, and the progress bar is in a separate form invoked by the child thread when uploading starts

如果这意味着您的子线程创建了 表单,那就是问题所在。您的子线程可能正在更新进度条值,但这只会使显示无效,而不一定会刷新显示。当控件的显示无效时,它只是记录下一次有机会时必须重绘它的显示。 刷新 是控件实际呈现到屏幕的时间。

更好的方法是在线程中创建进度条表单。

然后您的工作线程可以更新状态,您的主线程将刷新显示。

要记住一件事:如果您要更新在不同线程中创建的控件,则必须通过控件的调度程序进行。

var dispatcher = progressBar.Dispatcher;
dispatcher.BeginInvoke(new Action( () => { progressBar.Value = currentProgress }));


看到代码后编辑

您需要做的就是移动进度变量的创建,以便在创建工作线程之前由主线程对其进行实例化。


Progress win = new Progress();
win.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
win.Show();
System.Threading.Thread thread = new Thread(
   new ThreadStart(
         delegate()
         {
 // ...

关于c# - WPF 进度条未显示正确的进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5761474/

相关文章:

c# - 在 C# 中验证增值税号

wpf - 为特定控件设置 WPF 数据上下文

c# - 在 Caliburn IWindowManager 界面中集成闪烁任务栏

c# - 如何在 WPF 中绑定(bind)和刷新 UserControl 绑定(bind)?

c# - 当部分 View 位于共享文件夹中时,ASP.NET MVC '@model dynamic' 无法识别模型属性

c# - Windows 窗体可以在没有关闭按钮的情况下显示最小和最大按钮吗?

c# - CSS不适用于从ABC pdf创建pdf

c# - 当可以是 XElement 或 XAttribute 时如何转换 XPathEvalute?

wpf - 根据 Visual Studio 主题的变化更改图标

c# - WPF 在列表框中拖放,带有拖放位置的预览阴影