gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:57:13 24 4
gpt4 key购买 nike

我有一个应用程序,我要分块上传文件。我的前端是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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com