Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8099603
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T22:27:46+00:00 2026-06-05T22:27:46+00:00

I need a robust way of getting system uptime, and ended up using something

  • 0

I need a robust way of getting system uptime, and ended up using something as follows.
Added some comments to help people read it. I cannot use Task’s as this has to run on a .NET 3.5 application.

// This is a structure, can't be marked as volatile
// need to implement MemoryBarrier manually as appropriate
private static TimeSpan _uptime;

private static TimeSpan GetUptime()
{
    // Try and set the Uptime using per counters
    var uptimeThread = new Thread(GetPerformanceCounterUptime);
    uptimeThread.Start();

    // If our thread hasn't finished in 5 seconds, perf counters are broken
    if (!uptimeThread.Join(5 * 1000))
    {
        // Kill the thread and use Environment.TickCount
        uptimeThread.Abort();
        _uptime = TimeSpan.FromMilliseconds(
            Environment.TickCount & Int32.MaxValue);
    }

    Thread.MemoryBarrier();
    return _uptime;
}

// This sets the System uptime using the perf counters
// this gives the best result but on a system with corrupt perf counters
// it can freeze
private static void GetPerformanceCounterUptime()
{
    using (var uptime = new PerformanceCounter("System", "System Up Time"))
    {
        uptime.NextValue();
        _uptime = TimeSpan.FromSeconds(uptime.NextValue());
    }
}

The part I am struggling with is where should Thread.MemoryBarrier() be placed?
I am placing it before reading the value, but either the current thread or a different thread could have written to it. Does the above look correct?

Edit, Answer based on Daniel

This is what I eneded up implementing, thank you both for the insight.

private static TimeSpan _uptime;

private static TimeSpan GetUptime()
{
    var uptimeThread = new Thread(GetPerformanceCounterUptime);
    uptimeThread.Start();

    if (uptimeThread.Join(5*1000))
    {
        return _uptime;
    }
    else
    {
        uptimeThread.Abort();
        return TimeSpan.FromMilliseconds(
            Environment.TickCount & Int32.MaxValue);
    }
}

private static void GetPerformanceCounterUptime()
{
    using (var uptime = new PerformanceCounter("System", "System Up Time"))
    {
        uptime.NextValue();
        _uptime = TimeSpan.FromSeconds(uptime.NextValue());
    }
}

Edit 2

Updated based on Bob’s comments.

private static DateTimeOffset _uptime;

private static DateTimeOffset GetUptime()
{
    var uptimeThread = new Thread(GetPerformanceCounterUptime);
    uptimeThread.Start();

    if (uptimeThread.Join(5*1000))
    {
        return _uptime;
    }
    else
    {
        uptimeThread.Abort();
        return DateTimeOffset.Now.Subtract(TimeSpan.FromMilliseconds(
            Environment.TickCount & Int32.MaxValue));
    }
}

private static void GetPerformanceCounterUptime()
{
    if (_uptime != default(DateTimeOffset))
    {
        return;
    }

    using (var uptime = new PerformanceCounter("System", "System Up Time"))
    {
        uptime.NextValue();
        _uptime = DateTimeOffset.Now.Subtract(
            TimeSpan.FromSeconds(uptime.NextValue()));
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T22:27:49+00:00Added an answer on June 5, 2026 at 10:27 pm

    Thread.Join already ensures that writes performed by the uptimeThread are visible on the main thread. You don’t need any explicit memory barrier. (without the synchronization performed by Join, you’d need barriers on both threads – after the write and before the read)

    However, there’s a potential problem with your code: writing to a TimeSpan struct isn’t atomic, and the main thread and the uptimeThread may write to it at the same time (Thread.Abort just signals abortion, but doesn’t wait for the thread to finish aborting), causing a torn write.
    My solution would be to not use the field at all when aborting. Also, multiple concurrent calls to GetUptime() may cause the same problem, so you should use an instance field instead.

    private static TimeSpan GetUptime()
    {
        // Try and set the Uptime using per counters
        var helper = new Helper();
        var uptimeThread = new Thread(helper.GetPerformanceCounterUptime);
        uptimeThread.Start();
    
        // If our thread hasn't finished in 5 seconds, perf counters are broken
        if (uptimeThread.Join(5 * 1000))
        {
            return helper._uptime;
        } else {
            // Kill the thread and use Environment.TickCount
            uptimeThread.Abort();
            return TimeSpan.FromMilliseconds(
                Environment.TickCount & Int32.MaxValue);
        }
    }
    
    class Helper
    {
        internal TimeSpan _uptime;
    
        // This sets the System uptime using the perf counters
        // this gives the best result but on a system with corrupt perf counters
        // it can freeze
        internal void GetPerformanceCounterUptime()
        {
            using (var uptime = new PerformanceCounter("System", "System Up Time"))
            {
                uptime.NextValue();
                _uptime = TimeSpan.FromSeconds(uptime.NextValue());
            }
        }
    }
    

    However, I’m not sure if aborting the performance counter thread will work correctly at all – Thread.Abort() only aborts managed code execution. If the code is hanging within a Windows API call, the thread will keep running.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need a safe (i.e consistent, robust) way of detecting whether or not the
Need some help, please. I have a line of horizontal thumbnails loaded as ONE
Does anyone know of a way to script flash objects using WatiN? I need
I need a robust and simple way to remove illegal path and file characters
I want to use MAF in my project because I need a robust add-in
Need to insert selected text on the page into textarea. There must be some
Need to call a filter function on some options based on a radio selected
need help to create regular expression matching string www.*.abc.*/somestring Here * is wild card
need a quick help here. I have a series of hyperlinks all with the
I need a universal way to store dates and datetimes in several databases (for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.