Let's say that a class has a public int counter
field that is accessed by multiple threads. This int
is only incremented or decremented.
To increment this field, which approach should be used, and why?
lock(this.locker) this.counter++;
,Interlocked.Increment(ref this.counter);
,- Change the access modifier of
counter
topublic volatile
.
Now that I've discovered volatile
, I've been removing many lock
statements and the use of Interlocked
. But is there a reason not to do this?