根据 MSDN,Stopwatch
类实例方法对于多线程访问是不安全的。这也可以通过检查各个方法来确认。
但是,由于我只需要在我的代码中的几个位置使用简单的“经过时间”的计时器,我想知道它是否仍然可以无锁地完成,使用类似的东西:
public class ElapsedTimer : IElapsedTimer
{
/// Shared (static) stopwatch instance.
static readonly Stopwatch _stopwatch = Stopwatch.StartNew();
/// Stopwatch offset captured at last call to Reset
long _lastResetTime;
/// Each instance is immediately reset when created
public ElapsedTimer()
{
Reset();
}
/// Resets this instance.
public void Reset()
{
Interlocked.Exchange(ref _lastResetTime, _stopwatch.ElapsedMilliseconds);
}
/// Seconds elapsed since last reset.
public double SecondsElapsed
{
get
{
var resetTime = Interlocked.Read(ref _lastResetTime);
return (_stopwatch.ElapsedMilliseconds - resetTime) / 1000.0;
}
}
}
由于_stopwatch.ElapsedMilliseconds
基本上是对 的调用QueryPerformanceCounter
,我假设从多个线程调用它是安全的吗?与常规的不同之Stopwatch
处在于,这个类基本上一直在运行,所以我不需要像以前那样保持任何附加状态(“运行”或“停止”)Stopwatch
。
(更新)
在@Scott 在下面的答案中提出建议后,我意识到它Stopwatch
提供了一个简单的静态GetTimestamp
方法,它返回原始QueryPerformanceCounter
刻度。换句话说,代码可以修改成这样,这是线程安全的:
public class ElapsedTimer : IElapsedTimer
{
static double Frequency = (double)Stopwatch.Frequency;
/// Stopwatch offset for last reset
long _lastResetTime;
public ElapsedTimer()
{
Reset();
}
/// Resets this instance.
public void Reset()
{
// must keep in mind that GetTimestamp ticks are NOT DateTime ticks
// (i.e. they must be divided by Stopwatch.Frequency to get seconds,
// and Stopwatch.Frequency is hw dependent)
Interlocked.Exchange(ref _lastResetTime, Stopwatch.GetTimestamp());
}
/// Seconds elapsed since last reset
public double SecondsElapsed
{
get
{
var resetTime = Interlocked.Read(ref _lastResetTime);
return (Stopwatch.GetTimestamp() - resetTime) / Frequency;
}
}
}
澄清一下,这段代码的想法是:
- 有一种简单快捷的方法来检查自某个操作/事件以来是否已经过去了时间,
- 如果从多个线程调用方法,则不应破坏状态,
- 必须对操作系统时钟变化不敏感(用户变化、NTP 同步、时区等)
我会像这样使用它:
private readonly ElapsedTimer _lastCommandReceiveTime = new ElapsedTimer();
// can be invoked by multiple threads (usually threadpool)
void Port_CommandReceived(Cmd command)
{
_lastCommandReceiveTime.Reset();
}
// also can be run from multiple threads
void DoStuff()
{
if (_lastCommandReceiveTime.SecondsElapsed > 10)
{
// must do something
}
}