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

Posted by rwmnau on Stack Overflow See other posts from Stack Overflow or by rwmnau
Published on 2010-03-28T21:03:31Z Indexed on 2010/03/28 21:13 UTC
Read the original article Hit count: 298

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?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about locking