C#标签文本未更新

Ero*_*ocM 12 c# label sleep winforms

我有以下代码:

private void button1_Click(object sender, EventArgs e)
{
  var answer =
    MessageBox.Show(
      "Do you wish to submit checked items to the ACH bank? \r\n\r\nOnly the items that are checked and have the status 'Entered' will be submitted.",
      "Submit",
      MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
      MessageBoxDefaultButton.Button1);

  if (answer != DialogResult.Yes)
    return;

  button1.Enabled = false;
  progressBar1.Maximum = dataGridView1.Rows.Count;
  progressBar1.Minimum = 0;
  progressBar1.Value = 0;
  progressBar1.Step = 1;

  foreach (DataGridViewRow row in dataGridView1.Rows)
  {
    if ((string) row.Cells["Status"].Value == "Entered")
    {
      progressBar1.PerformStep();

      label_Message.Text = @"Sending " + row.Cells["Name"].Value + @" for $" + row.Cells["CheckAmount"].Value + @" to the bank.";
      Thread.Sleep(2000);
    }
  }
  label_Message.Text = @"Complete.";
  button1.Enabled = true;
}
Run Code Online (Sandbox Code Playgroud)

这是我正在创建的测试移植到我的应用程序.一切正常,但label_Message.text正在设置.它永远不会出现在屏幕上.它正在设置,我做了一个console.write来验证.它只是没有刷新屏幕.我最后也得到了"完整".

有人有主意吗?

Ada*_*lls 22

您正在UI线程上执行冗长的操作.您应该将其移动到后台线程(BackgroundWorker例如通过),以便UI线程可以在需要时执行重绘屏幕等操作.你可以作弊和执行Application.DoEvents,但我真的建议反对它.

这个问题和答案基本上就是你所要求的:
当在C#中执行任何其他操作时,表单不响应


小智 17

使用Label.Refresh(); 它节省了很多时间.这应该适合你


Jol*_*hic 5

在将 UI 线程返回到消息循环之前,Label 不会重新绘制。尝试Label.Refresh,或者更好的是,尝试将冗长的操作放在后台线程中,就像其他海报所建议的那样。