0

I'm developing a data aggregation object on a multi-thread environment, and I have the following situation:

int counts;

// This event is triggered by many threads at the same time
public void OnDataReceived(DataEvent evt)
{
   counts += evt.counts;
}

My question is whether it is safe to do

counts += evt.counts;

or I need something like

lock(lockObject)
{
   counts += evt.counts;
}
A.N.
  • 108
  • 6
  • 4
    += is *not* an atomic operation. You should use Interlocked.Increment. – mm8 May 02 '19 at 15:12
  • Nope. By the way, whether a particular operation in .NET is guaranteed to be atomic does not only depend on the operation itself, but also on the data type it is applied to... –  May 02 '19 at 15:13

1 Answers1

1

+= is not an atomic operation. You should use the Interlocked.Increment method.

mm8
  • 163,881
  • 10
  • 57
  • 88