动态标签for循环中的文本

本文关键字:文本 循环 标签 for 动态 | 更新日期: 2023-09-27 18:07:54

我用c#做了一个简单的WF,试图动态地改变标签。

然而,当我运行这段代码时,没有可见的变化,直到代码运行之后,然后它改变为"处理9"0-8从未显示。是因为它在循环内吗?

 private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {
            label9.Text = "Processing " + i.ToString();
            Thread.Sleep(1000);
        }
    }

编辑:X-Tech的代码工作,但当我试图将其纳入我的代码,我得到以下线程问题。我试图动态地改变标签。当进度条摇摆时,循环中的文本:

系统类型的异常。在System.Windows.Forms.dll中发生了InvalidOperationException,但未在用户代码中处理其他信息:跨线程操作无效:控制'progressBar1'从创建它的线程以外的线程访问。如果有此异常的处理程序,则程序可以安全地继续

我不确定如何攻击这个,因为我不是非常熟悉Task.Factory.StartNew()和Invoke语句。

编辑2:改编代码:

 Task.Factory.StartNew(() =>
 {
      for (int i = 0; i < lstFilesToZip.Items.Count; i++)
      {
          zipArray[i] = lstFilesToZip.Items[i].ToString();
          // Report progress.
          ExecuteSecure(() => label9.Text = "Processing :" + Path.GetFileNameWithoutExtension(lstFilesToZip.Items[i].ToString()));
          ExecuteSecure(() => progressBar1.PerformStep());
          string zipFileName = Path.GetFileName(zipArray[i]);
          string newFolder = txtDestinationFolder.Text + "''" + Path.GetFileNameWithoutExtension(zipArray[i]);
          //check to see if a directory with the file name for the zip file already exists, if not, it will create it
          if (Directory.Exists(newFolder) == false)
          {
                DirectoryInfo newPath = Directory.CreateDirectory(newFolder);
                if (lstCommonFiles.Items.Count > 0)
                {
                     //copies each file in the common file list to each new folder created, the boolean indicates that it will overwrite existing files (true) or won't (false)
                     for (int k = 0; k < lstCommonFiles.Items.Count; k++)
                     {
                          File.Copy(lstCommonFiles.Items[k].ToString(), (newFolder + "''" + Path.GetFileName(commonArray[k])), true);
                     }
                }
                //adds the zip file into the folder as well
                File.Copy(zipArray[i], (newFolder + "''" + zipFileName), true);
          }
    }
    if (txtCommonFiles.Text.Length <= 0)
    {
          string result = "There are no common files selected, would you still like to proceed?";
          DialogResult result1 = MessageBox.Show(result, "Common Files Missing", MessageBoxButtons.YesNo);
          if (result1 == DialogResult.No)
          {
               return;
          }
    }
    string[] dirs = Directory.GetDirectories(txtDestinationFolder.Text);
    // Grabs the folders in the newly created directory
    foreach (string dir in dirs)
          lstDestinationFinal.Items.Add(dir);
    //send sample file contents to preview window
    string[] sampleFiles = Directory.GetFiles(lstDestinationFinal.Items[0].ToString());
    //grabs the files
    foreach (string zipFiles in sampleFiles)
         lstSampleFile.Items.Add(zipFiles);
    ExecuteSecure(() =>tabControl1.SelectedTab = tabPage2);
});

}

和添加的方法:

 private void ExecuteSecure(Action action)
    {
        if (InvokeRequired)
        {
            Invoke(new MethodInvoker(() => action()));
        }
        else
        {
            action();
        }
    }

动态标签for循环中的文本

试试这个

Task.Factory.StartNew(() =>
{
     for (int i = 0; i < 10; i++)
     {              
          Invoke(new MethodInvoker(() => label9.Text = "Processing " + i.ToString()));
          Thread.Sleep(1000);
     }
});
编辑:

Task.Factory.StartNew(() =>
{
     for (int i = 0; i < 10; i++)
     {
          // Any GUI control which you want to use within thread,
          // you need Invoke using GUI thread. I have declare a method below for this
          //Now use this method as
          ExecuteSecure(() => label9.Text = "Processing " + i);
          ExecuteSecure(() => progressBar1.Value = i * 10);
          //... other code etc.
          Thread.Sleep(1000);
     }
});

//---
private void ExecuteSecure(Action action)
{
    if (InvokeRequired)
    {
        Invoke(new MethodInvoker(() => action()));
    }
    else
    {
        action();
    }
}

如果你想让你的UI实时更新,使用BackgroundWorker,否则所有的工作都在UI线程上完成,并且它保持冻结状态,直到工作结束。

private void button1_Click(object sender, EventArgs e)
    {
        int limit = 10;
        var bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;
        bw.DoWork += (s, ee) =>
        {
            for (int i = 0; i < limit; i++)
            {
                bw.ReportProgress(i);
                Thread.Sleep(1000);
            }
        };
        bw.ProgressChanged += (s, ee) => label9.Text = "Processing" + ee.ProgressPercentage.ToString();
        bw.RunWorkerAsync();
    }

不妨试试

 private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        label9.Text = "Processing " + i.ToString();
        Thread.Sleep(1000);
        Form1.Refresh();
    }
}

试试这个:

private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {
            label9.Text = "Processing " + i.ToString();
            Application.DoEvents();
            Thread.Sleep(1000);
        }
    }