如何处理" CrossThreadMessagingException"? [英] How can I handle "CrossThreadMessagingException"?

查看:494
本文介绍了如何处理" CrossThreadMessagingException"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码由标签组件显示在我的GUI中的时间序列。此代码是一个定时器的Tick事件。有时候,我得到Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException我不为什么?我怎么能捕获此异常?我怎样才能改变我的代码,以不产生这种例外?



  //计算并显示经过时间
时间跨度ElapsedTime = DateTime.Now - this.StartTime;
this.LabelElapsedTime.Text =的String.Format({} 0:00:{} 1:00:{} 2:00,ElapsedTime.Hours,ElapsedTime.Minutes,ElapsedTime.Seconds);


解决方案

最有可能的计时器事件正在访问从另一个控制螺纹,如从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; }
}

这篇关于如何处理&QUOT; CrossThreadMessagingException&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆