Jeff B
Jeff B

Reputation: 8982

Is SyncLock reetrant?

I have the following code in a class that manages refreshing some object automatically that also allows you to manually refresh. I want to make it thread-safe.

Public Function ForceRefresh() As Foo
  DoRefresh()
  ResetTimer()
  Return Me.CurrentFoo
End Function

Private Sub DoRefresh()
  Me._currentFoo = Me._retriever.GetTheFoo()
End Sub

I'm tempted to Synclock both of these methods:

... like this:

Private _syncRoot As New Object

Public Function ForceRefresh() As Foo
  Synclock _syncRoot
    'Snip ...
  End Synclock
End Function

Private Sub DoRefresh()
  Synclock _syncRoot
    'Snip ...
  End Synclock
End Sub

But then I end up trying to Synclock on _syncRoot twice when calling ForceRefresh... now if Synclock is reentrant then nesting these won't be an issue. The MSDN documentation page seems to imply that this is the case, but doesn't say it explicitly.

Note: I'm gonna give this a try myself, but I didn't see anything about this on StackOverflow and thought it was an useful question to have answered.

Upvotes: 3

Views: 864

Answers (1)

Hans Passant
Hans Passant

Reputation: 941605

The SyncLock statement uses Monitor.Enter() under the hood. The MSDN library says:

It is legal for the same thread to invoke Enter more than once without it blocking

Which means it is re-entrant. Easy to check btw.

Upvotes: 5

Related Questions