lock(new object()) -- Cargo cult or some crazy "language special case"?

C#Thread SafetyLocking

C# Problem Overview


I'm reviewing some code written by a consultant, and while dozens of red flags have already popped up, I can't wrap my head 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 is lock(new object()) doing here? Should have no effect whatsoever as it's always locking on another object, but this kind of locking is persistent throughout the code, even in non-copy-and-pasted parts. Is this some special case in the C# language that is compiled to something I don't know about, or has the programmer simply adopted some cargo cult that happened to work some time ago?

C# Solutions


Solution 1 - C#

I wouldn't be suprised if it was someone who 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
        // e.g. comands on the Mars Rover, or programs on iOS pre 4 / 5 ??
    }
}

and thought he could cut the number of lines.

I'd be very worried if that were the case though...

Solution 2 - C#

Here is similar question, and answer:

> Locks ensure mutual exclusion -- no more than one thread may hold the > lock at the same time. The lock is identified with a specific object > instance. You are creating a new object to lock on every time and you > don't have any way to inform any other thread to lock on that exact > same object instance. Therefore, your locking is useless.

Solution 3 - C#

It is probably useless. But there is the off chance it is there to create a memory barrier. Not sure if c# does lock elision or if it does whether it preserves the ordering semantics of the lock.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser434817View Question on Stackoverflow
Solution 1 - C#cjkView Answer on Stackoverflow
Solution 2 - C#JleruOHePView Answer on Stackoverflow
Solution 3 - C#benmmurphyView Answer on Stackoverflow