What is the difference between Syncroot and SyncLock Me?

Question about vb.Net multithreading:

What's the difference between

SyncLock syncRoot  
  ''# Do Stuff  
End SyncLock

th -

SyncLock Me  
  ''# Do Stuff  
End SyncLock
+5
source share
3 answers

All code that occurs in the block SyncLockis synchronized with all other code occurring inside the block SyncLockon the same object. Obviously Menot the same as syncRoot(i.e., I assume Me.SyncRootif yours Meis ICollection).

Code execution inside a block SyncLockon one object will not be synchronized with code inside a block SyncLockon another object.

Let's say you have this code:

' happening on thread 1 '
SyncLock myColl.SyncRoot
    myColl.Add(myObject)
End SyncLock

' happening on thread 2 '
SyncLock myColl.SyncRoot
    myColl.Remove(myObject)
End SyncLock

: Add Remove , (, , , , ).

, :

' happening on thread 1 '
SyncLock myColl.SyncRoot
    myColl.Add(myObject)
End SyncLock

' happening on thread 2 '
SyncLock myColl ' NOTE: SyncLock on a different object '
    myColl.Remove(myObject)
End SyncLock

Add Remove , . , .

, syncRoot? , ; , .

:

' happening on thread 1 '
SyncLock myColl
    myColl.Add(myObject)
End SyncLock

' happening on thread 2 '
SyncLock myColl
    ' Why you would have code like this, I do not know; '
    ' this is just for illustration. '
    myColl.Name = myColl.Name.Replace("Joe", "Bill")
End SyncLock

' happening on thread 3 '
SyncLock myColl
    myColl.Name = myColl.Name.Replace("Bill", "Joe")
End SyncLock

, . Add myColl; .

syncRoot: , - , / . , - , , , , , .

+5

Object.ReferenceEquals(syncRoot, Me) = True, . .

syncRoot ICollection.SyncRoot, , . . :

SyncLock collection.SyncRoot
  For Each item As Object in collection
  Next
End SyncLock

, .NET Me . , Me , API . , , , , , . .

, SyncLock , , SyncLock. , , SyncLock , .

+3

You are blocking different objects.

If other parts of your code (or internal code) are synchronized to SyncRootwhat they need, then you break things (for example, introducing errors in threads) by synchronizing to Me.

You should definitely sync with SyncRoot- why is he there.

+2
source

All Articles