Programming in C# – Managing Mulithreading

Synchronising Resources

  • Fairly easy to create multithreaded applications.
  • But sometimes you might want to read data from multiple threads simultaneously.
  • Application can vary because often operations are not atomic
  • Sometimes data needs to be synchronised
  • .NET has lock operating


This makes sure that code executes in the correct order, but it does have a hit on performance and should only be used if really needed.

Not supported by VB so blocks interoperability

The Interlocked class

Making operations atomic is the job of the Interlocked class that can be found in System.Threading namespace.

When using the Interlocked.increment and Interlocked.Decrement you create an atomic operation.

This guarantees that the increment and decrement operations are executed atomically.

If (Interlocked.Exchange(ref isInUse, 1) == 0) {}

This code retrieves the current value and immediately sets it to the new value in the same operation

CompareExchange does the same thing, apart from it checks to see if the expected value is there.

Instead of catching errors

Leave a Reply

Your email address will not be published. Required fields are marked *