且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理" CrossThreadMessagingException"?

更新时间:2022-10-19 07:44:25

最有可能的计时器事件正在访问从另一个控制螺纹,如从Timer.Interval事件。为了避免这个问题,Control.InvokeRequired属性必须检查,如果为真,控制访问必须使用委托从Control.Invoke方法来实现。



这方面的一个例子是如下:

 无效UpdateLabel (标签LBL,字符串文本)
{
如果(lbl.InvokeRequired)
{lbl.Invoke(新动作<标签,字符串>(UpdateLabel),新的对象[] {LBL,文本}); }
,否则
{lbl.Text =文本; }
}


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.Runtime.CrossThreadMessagingException" and I don't why? How can I catch this exception? How can I change my code in order to not get this exception?

    //Calculate and show elapsed time
    TimeSpan ElapsedTime = DateTime.Now - this.StartTime;
    this.LabelElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}", ElapsedTime.Hours, ElapsedTime.Minutes, ElapsedTime.Seconds);

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<Label, String>(UpdateLabel), new object[] { lbl, text }); }
    else
    { lbl.Text = text; }
}