如何处理“CrossThreadMessagingException”?
我有一个简单的代码,可以通过标签组件在 GUI 中显示时间序列。这段代码位于定时器的tick事件中。有时,我会收到“Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException”,但我不知道为什么?我怎样才能捕获这个异常?如何更改我的代码以避免出现此异常?
//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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
计时器事件很可能正在从另一个线程访问控件,例如从 Timer.Interval 事件。为了避免此问题,必须检查 Control.InvokeRequired 属性,如果为 true,则必须使用 Control.Invoke 方法中的委托来完成控件访问。
示例如下:
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: