Reputation: 35
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:
UpdateData()
always triggers the lock when called, locking both itself and GetInfo
GetInfo()
does not lock itself (so it can run simultaneously on multiple threads), but it DOES lock UpdateData
until it is finishedUpvotes: 1
Views: 109
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