How to properly lock a value type?

别等时光非礼了梦想. 提交于 2019-11-30 12:08:05

Use another object for the lock.

int valueType;
object valueTypeLock = new object();

void Foo()
{
    lock (valueTypeLock)
    {
        valueType = 0;
    }
}
Kent Boogaart

Your question is worded in such a way that it suggests to me that you don't entirely understand locking. You don't lock the data, you lock to protect the integrity of the data. The object you lock on is inconsequential. What matters is that you lock on the same object in other areas of your code that alter the data being protected.

JoshBerke

Depend on your situation you might be able to avoid using locks by leveraging System.Threading.Interlocked the same code in Jon's example becomes:

System.Threading.Interlocked.Exchange(valueType,0)

I'm always using a separate variable to lock on:

object syncObj = new object();

void Foo()
{
  lock(syncObj)
  {
    // do some stuff
  }
}

Locking on value-types doesn't make sense anyway because value-types are immutable and can't be modified. Locking on 'this' is also problematic because 'this' is visible to the outer world.

For some information about how the Monitor was originally intended to be used see Monitor (synchronization)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!