vb.Net multithreading question:
What is the difference between
SyncLock syncRoot
''# Do Stuff
End SyncLock
-and-
SyncLock Me
''# Do Stuff
End SyncLock
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
All code that happens within a
SyncLockblock is synchronized with all other code happening within aSyncLockblock on the same object. Obviously,Meis not the same assyncRoot(which is, I’m assuming,Me.SyncRoot, if yourMeis anICollection).Code happening within a
SyncLockblock on one object is not going to be synchronized with code within aSyncLockblock on a different object.Say you have this code:
The above is fine: the
AddandRemovecalls are synchronized, meaning they will not occur simultaneously (whichever gets called first will execute, and the second will not execute until the first is finished).But suppose you had this instead:
The above
AddandRemovecalls are not synchronized in any way, shape, or form. Thus there is no thread safety in the above code.Now, why does
SyncRootexist? Quite simply, because it makes sense to synchronize on the smallest scale necessary; i.e., there is no need to synchronize code that doesn’t actually need to be synchronized.Consider this example:
In the above, you are synchronizing more than necessary. The
Addcall really has nothing to do with the renaming of themyCollobject; thus the code does not need to be synchronized.This is the idea behind the
SyncRootproperty: it gives you an object whose entire purpose is to provide a common object with which modifications to/enumerations of the collection can be synchronized. Code that involves the collection in some other way — but which does not need to be synchronized with code that modifies or reads the contents of the collection — should be synchronized, where appropriate, on a different object.