Why use SyncLocks in .NET for simple operations when Interlocked class is available? Why use SyncLocks in .NET for simple operations when Interlocked class is available? multithreading multithreading

Why use SyncLocks in .NET for simple operations when Interlocked class is available?


You're correct; Interlocked should be used here, and will be faster than SyncLock.
However, the Interlocked class is not well-known.

However, there are situations where you need to use SyncLock and Interlocked will not help.


This is because no one knows about it. Spread the word!


The short answer is because using a Monitor lock (SyncLock in VB and lock { } in C#) not only assures that only one thread at a time can access the variable (or, in a strict sense, only one thread at a time can obtain a lock on the locking object), but it also creates the memory barrier required to ensure that reads on the variable aren't optimized away.

If you're never simply reading the value of the variable (in other words, all of your work is done through calls to Interlocked), then you'll be OK. However, if you need to be able to perform a normal read of the variable then the situation is more complicated. Lockless reads/writes are usually accomplished in C# using the volatile keyword. This instructs the compiler to read the value of the variable everywhere it's used, rather than optimizing away any of these reads into a local cache. Unfortunately there is no equivalent in VB.NET, so you'll have to use something else.

The accepted answer to this question should provide some more information on what you can do. In short, most people use SyncLock in VB.NET because it's easier and less complicated than the logic required to do it without SyncLock.