Lock (new object ()) - Cultural cult or some kind of crazy "language special occasion"?

I am reviewing the code written by a consultant, and when dozens of red flags have already appeared, I cannot wrap around the following snippet:

private void foo() { if (InvokeRequired) { lock (new object()) { if (m_bar!= null) Invoke(new fooDelegate(foo), new object[] { }); } } else { if(OnBazChanged != null) OnBazChanged(); } } 

What does lock (new object ()) do here? It should not have any effect, since it always blocks another object, but such a lock is preserved in all code, even in parts that are not copied and pasted. Is this some special case in C # that compiled to something I don’t know about, or asked the programmer to accept some piece of cargo that once worked?

+83
c # thread-safety locking
Aug 20 2018-12-12T00:
source share
3 answers

I would not be surprised if someone saw this:

 private readonly object lockObj = new object(); private void MyMethod() { lock(lockObj) { // do amazing stuff, so amazing it can only run once at a time // eg comands on the Mars Rover, or programs on iOS pre 4 / 5 ?? } } 

and thought that he could reduce the number of lines.

I would be very concerned if that were the case, though ...

+80
Aug 20 2018-12-12T00:
source share

Here's a similar question and answer:

Locks provide mutual exclusion - no more than one thread can lock at the same time. A lock is identified by a specific example object. You create a new object to lock every time, and you have no way to tell any other thread to the same instance of the object. Therefore, your lock is useless.

+14
Aug 20 2018-12-12T00:
source share

This is probably useless. But there is a chance to create a memory barrier. Not sure if C # blocks an elixir, or if it does, does it retain the semantics of blocking ordering.

+1
Sep 06
source share



All Articles