There’s been more than a couple times where I’ve wanted to use the Parallel class to take a collection and rip through it with multiple threads, but I’ve struggled with how to log the progress (especially the count of objects processed) easily.
Interlocked
.NET actually provides the solution in a static class called Interlocked, located in System.Threading. It provides some static functions to make atomic operations – thread-safe operations. Note that you have to pass the variable you want to change by reference. The result of the operation is returned, giving you a locally scoped value to work with in your threaded context.
Increment
Atomically increments the provided integer. Also works with int64s.
Decrement
Atomically decrements the provided integer. Also works with int64s.
Add
Adds the specified value to the provided integer. Also works with int64s. Similar to the Increment method, but can add any number.
Exchange
Sets the value of a provided object to the specified object. There are a lot of overloads for value types, but this method also provides a generic version to allow you to specify any type <T> that you want. Note that the original value is returned.
CompareExchange
Compares the value of a provided object to another value. If they are equal, the first value is replaced with a different specified value. Returns the original value.