请问"线程间操作无效: 从不是创建控件“labelTime”的线程访问它。"怎么解决?
我做了一个棋类游戏,想要分别对玩家和电脑计时,可是这里出现了错误,希望高手指教.
private System.Timers.Timer timerComputer = new System.Timers.Timer();
timerComputer.Elapsed += new ElapsedEventHandler(OnTimer);
timerComputer.Interval = 1;
timer1.Enabled = false;
MouseDown()
{
timerPerson.EnableD=false;
timerComputer.Enabled = true;
gm.ComputerPutChess();
timerComputer.Enabled = false;
timer1.Enabled = true;
}
public void OnTimer(Object source, ElapsedEventArgs e)
{
time2 = time2 + 1;
labelTime.Text = time2.ToString();
}
我想让他在窗体的label控件上显示时,出错:
线程间操作无效: 从不是创建控件“labelTime”的线程访问它。
请问大家如何解决!
------解决方案--------------------public void OnTimer(Object source, ElapsedEventArgs e)
{
Invoke(new EventHandle(TimerAction), source, e);
}
public void TimerAction(Object source, EventArgs e)
{
time2 = time2 + 1;
labelTime.Text = time2.ToString();
}