Lock (new object())——货物崇拜还是某种疯狂的“语言特例”?

我正在审阅一位顾问编写的一些代码,尽管已经出现了几十个危险信号,但我还是无法理解下面这段代码:

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

Lock (new object ())在这里做什么?应该没有任何效果,因为它总是锁定另一个对象,但是这种锁定在整个代码中都是持久的,即使在非复制和粘贴的部分中也是如此。这是 C # 语言中的某种特殊情况,它被编译成我不知道的东西,还是程序员只是采用了一些前一段时间偶然发生的货物崇拜?

4187 次浏览

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

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.

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.