Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
I'm having some slight problems with my uptime app. This is the lion's share of the code. A timer for the purpose of keeping it continuous updated.
 
        TimeSpan ts = TimeSpan.FromMilliseconds(Environment.TickCount);
 
        public void InitTimer()
        {
            timer1 = new Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Enabled = true;
            timer1.Interval = 1000;
            timer1.Start();
        }
However, when the application is loaded. Only the current uptime - up to the time the application was started - is shown. I don't quite see why it doesn't keeps counting.
        private void timer1_Tick(object sender, EventArgs e)
        {
            uptimeTxt.Text = ts.Days + "d" + ts.Hours + "h" +
                             ts.Minutes + "m" + ts.Seconds + "s";
        }
Posted 28-Dec-12 4:33am
Edited 28-Dec-12 4:43am
v2
Comments
Krunal Rohit at 28-Dec-12 10:37am
   
what are you getting from this code and what you actually want ??
leprechauny at 28-Dec-12 10:49am
   
I receive the uptime of the system since last reboot. And for the moment being I only get a static such. The counter doesn't go on ticking, so to speak.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

The value of ts is set once, which is why your uptime never increments. You're constantly showing the exact same value over and over again.
 
You need to set the value of ts (or get the value of Environment.TickCount) in the Timer Tick event handler.
  Permalink  
Comments
leprechauny at 28-Dec-12 10:56am
   
How silly of me! Cheers, Dave. Great!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

As far as in this block of code you might get an error:
private void timer1_Tick(object sender, EventArgs e)
        {
            uptimeTxt.Text = ts.Days + "d" + ts.Hours + "h" +
                             ts.Minutes + "m" + ts.Seconds + "s";
        }
 
Because you try to update upimeTxt text value from a particular thread . which is not a UI thread.
So basically , you must perform uptimeTxt.Text update workflow in UI synchronized code:
 
if(uptimeTxt.InvokeRequired){
this.Invoke((MethodInvoker)delegate {
    someLabel.Text = newText; // runs on UI thread
}
})
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 375
1 Abhinav S 333
2 OriginalGriff 330
3 sanket saxena 305
4 CPallini 175
0 Sergey Alexandrovich Kryukov 8,497
1 OriginalGriff 4,850
2 Peter Leow 3,839
3 Maciej Los 3,515
4 Er. Puneet Goel 3,107


Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 28 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid