C#标签文本未更新

我有以下代码:

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; } 

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

有人有主意吗?

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

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

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

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

此操作在UI线程中执行。 UI完成后才会更新。 要在发送期间进行更新,您必须在单独的线程中执行发送并从那里更新标签

当您在与用户界面元素运行的同一线程中进行密集计算/迭代时,通常会发生这种情况。 要解决这个问题,你需要有一个单独的线程来完成工作,并从那里相应地更新标签的值。 我发布了一个完整的源代码示例,但此刻我离开了我的开发机器。