标签文本未更新

我有一个带有状态栏的Windows窗体,它显示了当前的应用程序状态。 我有一个名为AppState的类,它在状态栏中更新了Label,并在处置它时将状态更改回“Ready”。

在我执行操作时的代码中:

using (AppState state = new AppState("Processing...")) { //Do some work that take some seconds } 

但标签保持不变。 我没有任何例外。 标签文本已更新,但在UI上,它会一直显示以前的值。 我在这里遗漏了什么?

santosc你是对的,这就是我唯一要做的事情。 这是AppState代码

 public class AppState : IDisposable { static string Default = "Ready"; public AppState(string status) { Form.StatusLabel.Text = status; } public void Dispose() { Form.StatusLabel.Text = Default; } } 

这总是一样的……

如果你想开始需要一段时间的事情,不要在你的GUI线程中执行它,否则你的GUI将会冻结(没有标签更新,没有resize,没有移动,没有任何东西)。

使用Application.DoEvents()在千位上填充代码也是一种不好的做法。

如果您有一些长时间运行的任务(长意味着> 1秒),您应该使用BackgroundWorker 。 也许它在开始时有点难,但如果你的程序变得更复杂,你会喜欢它。 由于这个事实,已经有好几次讨论,这里有一些示例代码的链接 。

现在您已经知道正确的工具(BackgroundWorker)来解决您的问题,您应该让它工作(或询问有关您的新特定问题的其他问题)。

看起来您想在设置StatusLabel文本字段值后放置Application.DoEvents() 。 这告诉Windows Forms处理表单的Windows事件队列,从而导致重新绘制更改。

为了“线程安全”使用Invoke ,并使用以下forms的InvokeRequired进行测试:

  // code outside the myForm:----------------------- if (myForm.InvokeRequired) myForm.Invoke(new ChangeLabelEventHandler(ChangeLabel), "teeeest"); else myForm.ChangeLabel("teeeest"); // code in the myForm:----------------------------- public delegate void ChangeLabelEventHandler(string newText); private void ChangeLabel(string newLabelText) { this.label1.Text = newLabelText; } 

我是C#的新手,但你为什么不能这样做:

 private void updateStatusBar(string status) { if (StatusLabel.InvokeRequired) { StatusLabel.Invoke((MethodInvoker)(() => { StatusLabel.Text = status; })); } else { StatusLabel.Text = status; } } 

想要更新状态时?

也许multithreading可以解决您的问题。

最简单的方法是使用BackgroundWorker。

原因是UI只能在UI线程没有其他任何操作时重绘。 你用你的计算阻止了它。

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