C# 形式 : progressbar doesn't show updates from thread doing work

标签 c# .net forms user-interface

问题

如何在一个线程中工作并更新主线程上的进度条?

摘要

下面是我尝试解决该问题的方法,但没有成功。我相信原因是更新在 Windows 消息泵中排队,但随后全部执行,因此更新发生得如此之快,用户看不到它们。

详细信息

我正在尝试创建一个 GUI 应用程序,它将在后台处理线程并更新进度条。我意识到使用后台工作进程会更简单,但这会剥夺我需要的一些灵活性。

我使用 InvokeRequired 和回调函数来处理从工作线程到主线程的调用,因此线程安全不应该成为问题。

在我的电脑上,当我单击“button1”时,工作线程大约需要 5 秒才能完成工作并将结果输出到 textbox1。在此期间,工作线程对 updateProgressBar 函数进行了大约 100 次调用。该函数正在执行:

progressBar1.Value = percent;
progressBar1.Update();
progressBar1.Refresh();
progressBar1.Invalidate();

但是,用户永远看不到这些命令的效果。我相信它们都被放入消息泵中以更新 GUI,但它们只是排队并立即执行。

我尝试过插休眠眠并调整正在完成的工作流程,但这没有帮助。如何刷新进度条更新?

请注意,这是一个为了说明问题而设计的示例。

代码

// Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Text.RegularExpressions;

namespace ProgressBarExample
{
    public partial class Form1 : Form
    {
        Thread processThread;
        delegate void updateGUICallback(int read, int unread);
        delegate void updateProgressBarCallback(int percent);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string input = "abc1234 123456 domain\abc1234 123 0\r\n";

            // Create 1048576 lines of input
            for (int i = 0; i < 20; i++)
                input += input;

            processThread = new Thread(new ParameterizedThreadStart(processData));
            processThread.Start(input);
        }

        private void processData(object input)
        {
            // Break the input on newlines
            string[] lines = Regex.Split((string)input, "\r\n");

            int readLines = 0;
            int unreadLines = 0;
            int maxLines = lines.Length;


            // Setup for regex
            Match match;
            string pattern = @"^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$";

            // Read each line of input
            for (int i = 0; i < maxLines; i++)
            {
                // Attempt a regex match
                match = Regex.Match(lines[i].Trim(), pattern);

                // If the line matches our expected entry, add it to the list
                if (match.Success)
                {
                    readLines++;
                }
                else
                {
                    unreadLines++;
                }

                // Update the progressbar every 10000 iterations
                if (i % 10000 == 0)
                {
                    updateProgressBar(i / maxLines);
                }
            }

            updateTextbox(readLines, unreadLines);
        }

        private void updateTextbox(int read, int unread)
        {
            if (textBox1.InvokeRequired)
            {
                updateGUICallback cb = new updateGUICallback(updateTextbox);
                this.Invoke(cb, new object[] { read, unread });
            }
            else
            {
                textBox1.Text = "Read: " + read + "\r\n" +
                    "Unread: " + unread;
            }
        }

        private void updateProgressBar(int percent)
        {
            if (progressBar1.InvokeRequired)
            {
                updateProgressBarCallback cb = new updateProgressBarCallback(updateProgressBar);
                this.Invoke(cb, new object[] { percent });
            }
            else
            {
                progressBar1.Value = percent;
                progressBar1.Update();
                progressBar1.Refresh();
                progressBar1.Invalidate();
            }
        }

    }
}

最佳答案

这在您设计的示例中可能是巧合,但是该行

updateProgressBar(i / maxLines);

实际上应该读作

updateProgressBar(100 * i / maxLines);

当您使用 Windows 窗体设计器的默认值时。我刚刚检查了修改情况,进度条定期更新,正如您(可能)希望的那样。

话虽如此,必须在每个方法体前面添加 Invoke()BeginInvoke() 苦差事确实会很尴尬,除非您提到的灵活性是最重要的是,我不会这么轻易地放弃BackgroundWorker 方法。

关于C# 形式 : progressbar doesn't show updates from thread doing work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9959289/

相关文章:

.net - 测试状态变化规则

django - 无法从 Django 小部件的模板获取 MEDIA_URL

javascript - 在 Webkit/Chrome 中检测 HTML5 数字控件更改的事件?

c# - Paypal 定期付款

c# - Entity Framework 核心 .Include() 问题

c# - Linq to Sql 查询两次返回相同的记录

.net - 托管可扩展性框架 (MEF) 与复合 UI 应用程序 block (CAB)

ruby-on-rails - 在 Rails form_for 辅助字段中使用 ParsleyJS

c# - C# 中超短且很棒的变量名

c# - Azure 服务总线中继和 http 协议(protocol)