且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

***线程安全的方式来增加一个整数高达65535

更新时间:2023-01-08 10:21:38

刚改变你的Int32值Int16的,如果你只需要2个字节。由于夏嘉曦去除这里他的答案是一些代码



  UINT16设为myVal = 0; 
对象myvalLock =新的对象();
....
锁(myvalLock){++设为myVal; }


I have a System.Timers.Timer that increments a counter every 3 seconds. Another thread may also set this variable to any value under some conditions.

Tried to use Interlocked.Increment but it does not have an overload for UInt16. The next thing in mind is lock, but I am not really sure how to make thread-safe access (read/write/increment) to this variable.

Edited: the code originally used an int, but changed to UInt16 as suggested

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++;
  }
}

Just change your Int32 value to Int16 if you only need 2 bytes. Since Shai removed his answer here's some code

UInt16 myval = 0;
Object myvalLock = new Object();
....
lock (myvalLock) { myval++; }