In multi-threaded applications, errors can creep in during the thread scheduler context-switching process. One of the main problems that arises is the update of the same variables by different threads. The methods of the System.Threading.Interlocked class in the mscorlib assembly help to protect against these kinds of errors. The methods of the Interlocked class do not throw exceptions, and so they are very helpful in applying simple state changes in a more performant way than using the lock statement that we've seen previously.
The methods available in the Interlocked class are as follows:
- CompareExchange:Compares two variables and stores the results in a different variable
- Add: Adds two Int32 or Int64 integer variables together and stores the result in the first integer
- Decrement: Decrements the Int32 and Int64 integer variable values and stores their results
- Increment:Increments theInt32...