How can I handle “CrossThreadMessagingException”?

后端 未结 1 885
深忆病人
深忆病人 2021-01-03 14:05

I have a simple code to show a time sequence in my GUI by a label component. This code is in the tick event of a timer. Sometimes, I get \"Microsoft.VisualStudio.Debugger.Ru

1条回答
  •  时光说笑
    2021-01-03 15:00

    Most likely the timer event is accessing the control from another thread, such as from the Timer.Interval event. To avoid this problem, the Control.InvokeRequired property must be checked, and if true, the control access must be done using a delegate from the Control.Invoke method.

    An example of this would be as follows:

    void UpdateLabel(Label lbl, String text)
    {
        if (lbl.InvokeRequired)
        { lbl.Invoke(new Action(UpdateLabel), new object[] { lbl, text }); }
        else
        { lbl.Text = text; }
    }
    

    0 讨论(0)
提交回复
热议问题