16.5. Interlocked Operations

Many processors support certain operations that are guaranteed by the runtime not to be interrupted. These operations are useful when you're dealing with threads, because you can use them without using locking. In the CLR these operations are encapsulated in the Interlocked class. This class exposes the Increment(), Decrement(), Exchange(), and Compare Exchange() methods, which can be used on the long and int data types.

In Listing 16.16, the Interlocked.Decrement operation is used to decrement the number of threads accessed in a thread-safe manner. The runtime guarantees that the interlocked decrement operation will not be interrupted.

You should use interlocked operations to improve performance, and avoid the use ...

Get .NET for Java Developers: Migrating to C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.