Using the interlocked classes to allow only a single thread access to a resource.
Using SyncLock (or Monitor in C#) to block all threads accessing a block of code can be overkill. SyncLock requires that all CPU instructions be cleared from the registers so that thread synchronisation can be performed safely and it also requires a lot of management by the .NET threading libraries.
In certain situation where multiple threads are running, you may require that just a single thread execute a piece of code at any one time. I've used this in situations where multiple threads are there for performance reasons but only 1 thread at a time should say clear down/refresh cache entries, but any of those threads could do the work.
Things to note in the code.
Note the definition of the member of _doingCacheCleardown it need to be shared.
Interlocked.Exchange returns the current value that was in the variable and then in a thread safe manner put the value passed in to the variable. So thats why we check to see if the value returned from Interlocked.Exchange is zero, if it is not then some other thread is in the process of executing the code block.
Note also that we always reset the value of _doingCacheCleardown to 0, even if an error happens in the code block, because if we don't nothing would ever execute that code block again until that value of _doingCacheCleardown was set to zero.
The code example, is pretty small.
Public Class CacheManager
Private Shared _doingCacheCleardown As Integer = 0
Private Sub RevokeItemsFromCache()
Try
If System.Threading.Interlocked.Exchange(_doingCacheCleardown, 1) = 0 Then
' Do something that only a single thread should do.
Console.WriteLine("Say hello from thread id {0}", System.Threading.Thread.CurrentThread.ManagedThreadId)
End If
Catch ex As Exception
Throw
Finally
' Always reset the value to zero, if we don't nothing will ever get in this code block
' again.
System.Threading.Interlocked.Exchange(_doingCacheCleardown, 0)
End Try
End Sub
End Class