The Interlocked class is a simple statement used for atomic manipulation of variables. If i++ is not thread safe, it obtains a value from memory, then adds 1 to the value and then saves the value back into memory. These operations may be interrupted by the thread scheduler. The Interlocked class provides thread-safe behavior for methods of increment, decrement, change, and read.
Using interlocked analogy with other synchronization techniques is quicker. However, you can only use it on a simple sync issue.
For example, when assigning a new value to a somestate variable to prevent a value of NULL we do not use lock locks, and we choose to use a faster interlocked class (code file Synchronizationsamples/sharedstate.cs):
Lock (This) {if (somestate = = null) {somestate = newstate; }}
Interlocked.compareexchange<somestate> (refnull);
Use the Lock method:
public int state{ get { lock (this) { return ++state; }}}
Interlocked Way:
Public int state{ get { return interlocked.increment ( ref State);} }
C # 5.0 and. Net 4.5 Learning (iii) interlocked