Monitor.TryEnter Tips

We use Parallel Extensions in one part of our vb.net application to extract data from under the dictator (string, datatable). In the method, we use Monitor.TryEnter to retrieve the table. Sometimes we get the error "Object synchronization method was called from an unsynchronized block of code." Here's 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 get a lock before trying to get out of it? I think an error occurs because I'm trying to make monitor.exit even if monitor.tryenter is false.

+3
source share
1 answer

Monitor.Exit. , TryEnter , Monitor.Exit , finally. . .

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
+3

Source: https://habr.com/ru/post/1757277/


All Articles