Reshef’s tip of the day

.net development tips

Tip of the day: Interlocked

The Interlocked class in .net is a static class that provides type operation that are performed atomically.

By providing this, it can help solve simple multithreading scenarios since:

1) It removes the chance of deadlocks that can be caused by using the lock keyword.

2) It has better performance than the lock keyword.

3) Simpler (and less) syntax.

Lets take a look at a scenario where you would like to count how many times a method is called while a program runs (multithreaded environment):

private static int methodCallsCounter = 0;
…

public void SomeMethod()
{
    System.Threading.Interlocked.
        Increment(ref methodCallsCounter);
    …
}

The Interlocked class has a set of methods to manipulate data. A complete documentation and a full example can be found here.

Talking about multithreading and locks, I suggest reading this. It describes very important points about locking.

Leave a Reply

Jajah is the VoIP player that brought you web-activated telephony.