In my class I'm trying to display the elapsed time as my label on a windows form. I've been reading up on all the different articles online and have tried these three methods all with the same result:
1. Using the System.Timers class
2. Built in Timer sub-class
3. Defining directly inside of my class the StartTime, etc. variables.
All of these still result in the following error:
Cross-thread operation not valid: Control 'User_Interface' accessed from a thread other than the thread it was created on.
Currently, my windows form is being called by another class, but I'm not sure if this is the cause of the problem.
This is a sample of the code that I'm currently using to show the elapsed time:
Expand|Select|Wrap|Line Numbers
- private void OnTimedEvent (object source, ElapsedEventArgs c)
- {
- TimeSpan time;
- currentTime = DateTime.Now;
- time = currentTime - startTime;
- int days = time.Days;
- double hours = time.Hours;
- double mins = time.Minutes;
- double secs = time.Seconds;
- if (days != 0)
- {
- elapsedTime += days.ToString() + ":";
- }
- if (hours != 0)
- {
- elapsedTime += hours.ToString("00") + ":";
- }
- elapsedTime += mins.ToString("00") + ":";
- elapsedTime += secs.ToString("00");
- UI_Time_label.Text = elapsedTime;