Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best thread-safe way to increment an integer up to 65535

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++;
  }
}
like image 217
fxam Avatar asked Jan 02 '12 07:01

fxam


2 Answers

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++; }
like image 32
Jesus Ramos Avatar answered Sep 28 '22 08:09

Jesus Ramos


I would just use an UInt32 with Interlocked.Increment and cast it to UInt16 after every read access.

like image 102
Ringding Avatar answered Sep 28 '22 10:09

Ringding