Joseph Nields
Joseph Nields

Reputation: 5661

How to lock primitive static fields in VB.NET

I know you can obtain a lock instance members like so:

SyncLock [Object]
    [Object].mutate()
End SyncLock

but how do you lock static fields?

(e.g. to make [Object's Class].[static field] = [new value] thread-safe)

I can't find anything online for VB.

The field is a primitive type.

Upvotes: 1

Views: 402

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

As long as the object is a reference type, you can simply lock that object:

SyncLock [Class].[Object]
    ' … edit object
End SyncLock

Depending on your situation this may be the correct thing to do. However, be aware that this should ideally only be done on private objects, inside the class. Otherwise you have no guarantee that every client is going to lock the object correctly.

Whether your field is a primitive type isn’t important here, except that most primitive types are value types, and you cannot lock those. So, assuming that your type is a value type, you have to resort to a separate lock object as discussed in the comments:

Private Shared ReadOnly LockObj As New Object()

But, to clarify, locking on LockObj does not magically lock the rest of the class. It just provides a protocol for locking, and as long as every thread accessing the fields respects this protocol, you’re safe. Here’s an example:

Class Foo
    Private Shared ReadOnly LockObj As New Object()
    Private Shared MyValue As Integer = 1

    Public Shared Sub UpdateValue()
        SyncLock LockObj
            MyValue += 1
        End SyncLock
    End Sub

    Public Shared Function ReadValue() As Integer
        SyncLock LockObj
            Return MyValue
        End SyncLock
    End Function
End Class

As long as every thread uses only UpdateValue and ReadValue to access MyValue, you’re safe from race conditions.

Upvotes: 3

Related Questions