Click here to Skip to main content
15,922,630 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C#
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.
C#
private void timer1_Tick(object sender, EventArgs e)
{
    uptimeTxt.Text = ts.Days + "d" + ts.Hours + "h" +
                     ts.Minutes + "m" + ts.Seconds + "s";
}
Posted
Updated 28-Dec-12 4:43am
v2
Comments
[no name] 28-Dec-12 10:37am    
what are you getting from this code and what you actually want ??
leprechauny 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.

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.
 
Share this answer
 
Comments
leprechauny 28-Dec-12 10:56am    
How silly of me! Cheers, Dave. Great!
As far as in this block of code you might get an error:
C#
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:

C#
if(uptimeTxt.InvokeRequired){
this.Invoke((MethodInvoker)delegate {
    someLabel.Text = newText; // runs on UI thread
}
})
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900