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: