使用Windows窗体的C#中的实时计数器

本文关键字:实时 计数器 窗体 使用 Windows | 更新日期: 2023-09-27 18:21:06

如何在Windows Form中为读取的行计数?

当我执行Windows Form时,这个计数器会在应用程序处理每个数据时显示。

样本代码

    public Form1()
    {
        InitializeComponent();
        setMessage(string.Empty, this.lblErro);
    }
   private void button1_Click(object sender, EventArgs e) 
   { 
     for (int i = 0; i <= xmlnode.Count - 1; i++)
     {
          int cont = i;                    
          ThreadPool.QueueUserWorkItem(_ =>
          {
              setMessage(++cont + " of " + xmlnode.Count, this.lblCounter);                        
          });
      }
       void setMessage(string message, Label lbl)
        {
            if (InvokeRequired)
            {
                Invoke((MethodInvoker)(() => setMessage(message, lbl)));
            }
            else
            {
                lbl.Text = message;
            }
        }
     }

我尝试了上面的代码,但没有成功。应用程序处理所有数据时仍显示消息

使用Windows窗体的C#中的实时计数器

您需要运行以下循环:

for (int i = 0; i <= xmlnode.Count - 1; i++)
{
    ...
}

关闭主UI线程。有很多方法可以实现这一点,但无论出于什么原因,我更喜欢BackgroundWorker。你可以这样做:

BackgroundWorker _worker = new BackgroundWorker();

然后在ctor:中

_worker.DoWork += (s, e) =>
{
    // place the entire for loop in here
}

现在,当你准备好运行它时,就这样做:

_worker.RunWorkerAsync();

尝试将循环放入:

ThreadPool.QueueUserWorkItem(_ =>  {
    for (int i = 0; i <= xmlnode.Count - 1; i++)
     {
          int cont = i;   
          setMessage(++cont + " of " + xmlnode.Count, this.lblCounter);                        
     }
 });