Sean Stephens
Sean Stephens

Reputation: 35

.Net Synclock Read-Methods Only When Updating

How can I allow a method to be called simultaneously from multiple threads without locking, but where it WILL lock while a different method is called?

Example:

Private DataLock As New Object()

Private Function GetInfo() As String
    SyncLock DataLock 
        'Read existing data and return a String
    End SyncLock
End Function

Private Sub UpdateData()
    SyncLock DataLock 
        'Update/Change existing Data
    End SyncLock
End Sub

How do I modify the above code so that:

Upvotes: 1

Views: 109

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54427

This is the direct analogue to the code you posted using the ReaderWriterLockSlim class:

Private dataLock As New ReaderWriterLockSlim()

Private Function GetInfo() As String
    dataLock.EnterReadLock()

    Try
        'Read existing data and return a String
    Finally
        dataLock.ExitReadLock()
    End Try
End Function

Private Sub UpdateData()
    dataLock.EnterWriteLock()

    Try
        'Update/Change existing Data
    Finally
        dataLock.ExitWriteLock()
    End Try
End Sub

You might want to consider the Try methods though, which allow you to specify a maximum time to wait for the lock.

Upvotes: 3

Related Questions