我试图在窗体上显示一个错误,并使用计时器在一秒钟内删除错误。我有:
const string sendingError = "currently sending a message please wait";
System.Timers.Timer timer = new System.Timers.Timer(1000);
commandValues.errorList[sendingError] = sendingError;
commandValues.updateErrorList();通过使用错误消息更新标签,这将发挥应有的作用。
timer.Elapsed += ((source, e) =>
{
var INDEX = Form.ActiveForm.Controls.IndexOfKey("errorBox");
Debug.WriteLine(Form.ActiveForm.Controls[INDEX]);
Form.ActiveForm.Controls[INDEX].Text = "";
Debug.WriteLine("2" + Form.ActiveForm.Controls[INDEX]);
});
timer.Enabled = true;
timer.Start();调试行显示
1System.Windows.Forms.Label, Text: currently sending a message please wait
1System.Windows.Forms.Label, Text: currently sending a message please wait
1System.Windows.Forms.Label, Text: currently sending a message please wait
1System.Windows.Forms.Label, Text: currently sending a message please wait
// etcetera如您所见,第二个调试行永远不会显示。断点一致认为,当我试图更改标签时,它会离开委托。
我是C#新手,所以任何建议都会很感激,但我特别想知道如何在超时后编辑主表单,以及为什么我的尝试失败了。
发布于 2015-04-28 15:58:39
您应该将UI修改从Timer thread分派到UI Thread。不允许从其他线程修改UI元素。
要做到这一点,您需要调用this.BeginInvoke。
https://stackoverflow.com/questions/29924168
复制相似问题