Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# lock question: lock(this) vs lock(SyncRoot)

Tags:

c#

locking

I have a class with a field of type collection.

Questions:

  1. if I lock(this), do I effectively lock the collection too?
  2. what is more efficient, to do lock(this) or to create a SyncRoot object and do lock(SyncRoot)?
like image 439
Nestor Avatar asked Jun 28 '11 17:06

Nestor


People also ask

What C is used for?

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 ...

Is C language easy?

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 in C language?

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.

What is C full form?

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.


2 Answers

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. locking 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?

like image 165
jason Avatar answered Sep 27 '22 23:09

jason


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.

like image 42
Ray Avatar answered Sep 28 '22 00:09

Ray