Is this a correct Interlocked synchronization design? Is this a correct Interlocked synchronization design? multithreading multithreading

Is this a correct Interlocked synchronization design?


Yes, it looks safe because int is an atomic type here. But I would still advice replacing

private static int _isSampling;

with

private static object _samplingLock = new object();

and use :

lock(_samplingLock){    Sample sample = new Sample();    sample.PerformSampling(automation);   _lastSample = sample;}

Simply because it is the recommended pattern and also makes sure all access to _lastSample is treated correctly.

NB: I would expect comparable speed, lock uses the managed Monitor class that uses Interlocked internally.

Edit:

I missed the back-off aspect, here is another version :

   if (System.Threading.Monitor.TryEnter(_samplingLock))   {     try     {         .... // sample stuff     }     finally     {          System.Threading.Monitor.Exit(_samplingLock);     }   }


I usually declare a volatile bool and do something like:

private volatile bool _isBusy;private static Sample _lastSample;private Sample DoSomething(){     lock(_lastSample)     {       if(_isBusy)          return _lastSample;       _isBusy = true;     }     try     {       _lastSample = new sameple//do something     }     finally     {        lock(_lastSample)        {           _isBusy = false;        }     }     return _lastSample;}