Search code examples
c#.netconcurrencyparallel-processinglinearization

Does .NET have a check-and-set operator?


Where are the basic concurrency primitives in .Net?

Specifically I want to use a Check and Set operator.


Solution

  • You need to look at the Interlocked class in the System.Threading namespace. The CompareExchange is the method you're looking for.

    It has the form CompareExchange(target, value, comparand) which in pseudo-code means if(target==comparand) target=value;.

    There are also a load of other atomic methods on the Interlocked class that are useful, such as Increment, Decrement, Add and Exchange.