4

我需要一种可靠的方法来获得系统正常运行时间,并最终使用如下方法。添加了一些评论以帮助人们阅读它。我不能使用 Task,因为它必须在 .NET 3.5 应用程序上运行。

// 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());
    }
}

我正在努力的部分是应该Thread.MemoryBarrier()放在哪里?我在读取值之前放置它,但是当前线程或不同的线程可能已经写入它。以上看起来正确吗?

编辑,根据丹尼尔回答

这就是我最终实现的,谢谢你们的洞察力。

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());
    }
}

编辑 2

根据 Bob 的评论更新。

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()));
    }
}
4

2 回答 2

2

Thread.Join已经确保 uptimeThread 执行的写入在主线程上可见。您不需要任何显式的内存屏障。(如果没有 执行的同步Join,您将需要两个线程上的障碍 - 在写入之后和读取之前)

但是,您的代码存在一个潜在问题:写入TimeSpan结构不是原子的,主线程和 uptimeThread 可能同时写入它(Thread.Abort只是发出中止信号,但不等待线程完成中止),导致写入撕裂。我的解决方案是在中止时根本不使用该字段。此外,多个并发调用GetUptime()可能会导致相同的问题,因此您应该改用实例字段。

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());
        }
    }
}

但是,我不确定中止性能计数器线程是否会正常工作 -Thread.Abort()只会中止托管代码执行。如果代码在 Windows API 调用中挂起,线程将继续运行。

于 2012-06-19T13:48:53.587 回答
2

.NET 中的 AFAIK 写入是易失性的,因此您需要内存栅栏的唯一地方是在每次读取之前,因为它们需要重新排序和/或缓存。引用Joe Duffy 的帖子

作为参考,以下是我所理解的规则,尽可能简单地说明:

Rule 1: Data dependence among loads and stores is never violated.
Rule 2: All stores have release semantics, i.e. no load or store may move after one.
Rule 3: All volatile loads are acquire, i.e. no load or store may move before one.
Rule 4: No loads and stores may ever cross a full-barrier. 
Rule 5: Loads and stores to the heap may never be introduced.
Rule 6: Loads and stores may only be deleted when coalescing adjacent loads and 
stores from/to the same location.

请注意,根据这个定义,非易失性负载不需要有任何类型的障碍与其相关联。因此负载可以自由地重新排序,并且写入可以在它们之后移动(尽管不是在之前,由于规则 2)。使用此模型,您真正需要规则 4 提供的完整屏障强度的唯一真实情况是在存储后跟易失负载的情况下防止重新排序。没有障碍,说明可能会重新排序。

于 2012-06-19T13:56:49.963 回答