我有一个System.Timers.Timer,每3秒增加一次计数器。在某些条件下,另一个线程可能会将此变量设置为任何值。
尝试使用Interlocked.Increment,但它没有UInt16的重载。接下来想到的是锁(lock),但我不确定如何对该变量进行线程安全的访问(读/写/增量)。
编辑:代码最初使用int,但根据建议更改为UInt16。
尝试使用Interlocked.Increment,但它没有UInt16的重载。接下来想到的是锁(lock),但我不确定如何对该变量进行线程安全的访问(读/写/增量)。
编辑:代码最初使用int,但根据建议更改为UInt16。
private volatile System.UInt16 mCounter = 0;
private readonly object mCounterLock = new object();
public System.UInt16 Counter {
get {
lock (mCounterLock) {
return mCounter;
}
}
set {
lock (mCounterLock) {
mCounter = value;
}
}
}
private System.Timers.Timer mCounterTimer;
void mCounter_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
lock (mCounterLock) {
Counter++;
}
}
uint16
。但现在是吗?这有意义吗? - jalf