Reputation: 513
We are using Parallel Extensions in one part of our vb.net app to retrieve an datatable from a dictonary(of string, datatable). In the method to retrive the table, we are using Monitor.TryEnter. Sometimes, we get the error "Object synchronization method was called from an unsynchronized block of code." Here is what our method looks like:
Try
if Monitor.TryEnter(_ProductCollection, 200) = true then
_ProductCollection.TryGetValue(name, ReturnValue)
end if
Finally
Monitor.Exit(_ProductCollection)
End Try
Should I try to implement a loop to make sure we obtain the lock, before trying to exit it? I am thinking the error is being thrown because I am trying to do the monitor.exit even if the monitor.tryenter is false.
Upvotes: 3
Views: 1528
Reputation: 48949
The error is being thrown from the Monitor.Exit
call. What is happening is that TryEnter
timesout occasionally and the lock is not acquired, but Monitor.Exit
is always called since it is the finally
block. That is the problem. Here is how you can fix it.
Dim acquired As Boolean = False
Try
acquired = Monitor.TryEnter(_ProductionCollection, 200)
If acquired Then
' Do your stuff here.
End If
Finally
If acquired Then
Monitor.Exit(_ProductionCollection)
End If
End Try
Upvotes: 3