I have a class with a field of type collection.
Questions:
lock(this)
, do I effectively lock the collection too?lock(this)
or to create a SyncRoot
object and do lock(SyncRoot)
?C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
History: The name C is derived from an earlier programming language called BCPL (Basic Combined Programming Language). BCPL had another language based on it called B: the first letter in BCPL.
Don't lock
on this
. It could be the case that someone else has used the instance as a lock
object too. Use specifically designated lock
objects.
1) if I lock(this), do I effectively lock the collection too?
No.
2) what is more efficient, to do lock(this) or to create a SyncRoot object and do lock(SyncRoot) ?
Efficient? Focus on semantics. lock
ing on this
is dangerous. Don't do it. The difference in performance, if any, is not material.
Seriously, it's akin to asking, what will get me to my destination faster, driving 100 MPH the wrong way down the freeway, or walking?
Always use lock(_syncRoot)
.
Where _syncRoot
is a private field (just has to be an object).
This is no difference in terms of efficiency, but you're better to have a private field that you're in control of to lock on. If you lock on this
, another object may also be locking on it.
See Why is lock(this) {...} bad? for a much better explanation. Also have a look at the msdn article on lock.
By locking on a collection, you aren't doing anything to stop it from being changed. A misunderstanding you might have, is that lock doesn't do anything special to stop that object being changed, it only works if every critical piece of code also calls lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With