C#, System.Timers.Timer的ElapsedEventHandler事件中,调用界面上的label时报错:
Cross-thread operation not valid: Control 'tbxCurrSection' accessed from a thread other than the thread it was created on.
跨线程调用的问题。
想起之前用Thread.start时的解决方案,用InvokeRequired来判断,在这里不行,继续报错。
if (tbxCurrSection.InvokeRequired) //不行
{
MethodInvoker ivk = updateInfoSection;
tbxCurrSection.BeginInvoke(ivk);
}
在stackoverflow上找到了答案:
https://stackoverflow.com/questions/24085983/how-to-fix-a-cross-thread-exception-in-c
设置timer的SynchronizingObject属性
//...
timerL2.SynchronizingObject = this; //this就是窗体本身
//...
问题解决。