代码之家  ›  专栏  ›  技术社区  ›  Roee Adler

在繁忙的循环中如何显示进度?

  •  10
  • Roee Adler  · 技术社区  · 16 年前

    我有一个从外部源读取大量数据的循环。这个过程大约需要20秒,我想向用户显示进度。我不需要任何花哨的进度条,所以我选择将我的进度绘制在一个标签上,上面写着“步骤1/1000”,然后改为“步骤2/1000”等。

    我的代码如下所示:

    // "count" is the number of steps in the loop, 
    // I receive it in previous code
    
    String countLabel = "/"+count.ToString();
    
    for (i = 0; i < count; i++)
    {
        ... do analysis ...
        labelProgress.Content = "Step "+i.ToString()+countLabel
    }
    

    但是,在分析过程中,屏幕被“卡住”,并且进度不会显示为前进。我从C++中了解了我过去的行为,在这里我可能会有一个单独的线程显示进度条从循环中接收通知,或者某种形式的重绘/刷新,或者强制窗口/应用程序处理它的消息队列。

    用C语言做这件事的正确方法是什么?我没有绑定到标签,所以如果有一个简单的进度条弹出屏幕,我可以使用而不是这个标签,它也将是伟大的…

    谢谢

    3 回复  |  直到 7 年前
        1
  •  11
  •   user7116    16 年前

    将工作移至 BackgroundWorker 并使用 ReportProgress 方法。

    for (i = 0; i < count; i++)
    {
        ... do analysis ...
        worker.ReportProgress((100 * i) / count);
    }
    
    private void MyWorker_ProgressChanged(object sender,
        ProgressChangedEventArgs e)
    {
        taskProgressBar.Value = Math.Min(e.ProgressPercentage, 100);
    }
    
        2
  •  3
  •   Dan    16 年前
        //Create a Delegate to update your status button
        delegate void StringParameterDelegate(string value);
        String countLabel = "/" + count.ToString();
        //When your button is clicked to process the loops, start a thread for process the loops
        public void StartProcessingButtonClick(object sender, EventArgs e)
        {
            Thread queryRunningThread = new Thread(new ThreadStart(ProcessLoop));
            queryRunningThread.Name = "ProcessLoop";
            queryRunningThread.IsBackground = true;
            queryRunningThread.Start();
        }
    
        private void ProcessLoop()
        {
            for (i = 0; i < count; i++)
            {
                ... do analysis ...
                UpdateProgressLabel("Step "+i.ToString()+countLabel);
            }
        }
    
        void UpdateProgressLabel(string value)
        {
            if (InvokeRequired)
            {
                // We're not in the UI thread, so we need to call BeginInvoke
                BeginInvoke(new StringParameterDelegate(UpdateProgressLabel), new object[] { value });
                return;
            }
            // Must be on the UI thread if we've got this far
            labelProgress.Content = value;
        }
    
        3
  •  2
  •   ean5533    13 年前

    由于当前线程的优先级高于最终设置标签的UI线程,因此不会更新UI;)。所以,直到你的线程完成你的东西,它将更新你的标签在最后。

    对于我们来说幸运的是,每个WPF控件上都有一个Dispatcher属性,它允许您用另一个优先级启动一个新线程。

    labelProgress.Dispatcher.Invoke(DispatcherPriority.Background,
                        () => labelProgress.Content = string.Format("Step {0}{1}", i, countLabel));
    

    这会在后台触发一个线程,从而完成任务!你也可以试试其他的 DispatcherPriority 选项

    ps我还冒昧地添加了一个匿名方法,并在一定程度上修复了字符串解析。希望你不介意……