How to determine system uptime without overflow issues in C#

.NET programming topics
Post Reply
Cyclops
Lieutenant
Lieutenant
Posts: 71
Joined: Wed Jul 15, 2009 1:48 pm
Location: London

How to determine system uptime without overflow issues in C#

Post by Cyclops » Thu Dec 31, 2009 9:36 am

Environment.TickCount returns a 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the computer was started. But this value can overflow for systems that stay up for days at a time.

To avoid this overflow problem, you can query the "System Up Time" performance counter:

Code: Select all

public TimeSpan SystemUpTime()
{
  PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");

  // You've got to call this twice. First time it returns 0 and the second time it returns the real info.
  upTime.NextValue();
   
  return TimeSpan.FromSeconds(upTime.NextValue());
}
Post Reply

Return to “.NET Programming”