I've been doing simple multi-threading in VB.NET for a while, and have just gotten into my first large multi-threaded project. I've always done everything using the Synclock
statement because I didn't think there was a better way.
I just learned about the Interlocked
Class - it makes it look as though all this:
Private SomeInt as Integer
Private SomeInt_LockObject as New Object
Public Sub IntrementSomeInt
Synclock SomeInt_LockObject
SomeInt += 1
End Synclock
End Sub
Can be replaced with a single statement:
Interlocked.Increment(SomeInt)
This handles all the locking internally and modifies the number. This would be much simpler than writing my own locks for simple operations (longer-running or more complicated operations obviously still need their own locking).
Is there a reason why I'd rolling my own locking, using dedicated locking objects, when I can accomplish the same thing using the Interlocked
methods?
C# lock in thread The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.
It lets you do small and well-defined operations safely in a multi-threaded environment: for instance, if you want two threads to increment the same variable, you can use Interlocked to do it instead of acquiring a heavyweight lock and using the "regular increment".
SyncLock prevents each thread from entering the block until no other thread is executing it. The most common use of SyncLock is to protect data from being updated by more than one thread simultaneously.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With