C# - Locking a resource when obtained from dictionary

戏子无情 提交于 2019-12-04 11:50:44

Does getting and locking a value (ClientObject) from the dictionary in one thread mean that other threads will respect that lock? In other words, does .net see a value in the dictionary as a single resource (and not a copy) and will therefore respect a lock on that resource in all threads?

It depends on the type - if a reference type then yes, if a value type no. This is also why you should never, ever lock on a value type since the value type will be boxed and any subsequent attempts to lock on that value will actually acquire a lock on a different object.

One more question, when removing a resource from the dictionary - should I lock it before performing Remove()

Yes, you should lock before any operation that mutates the state of the object.

As a side note - are you sure that this setup is the best possible solution to your problem? Mutable objects shared across threads tend to create more problems then they solve.

If you are adding or removing items from the dictionary, lock the dictionary.

When you put an object in the dictionary, you are putting a REFERENCE to that object in the dictionary. To prevent that object from being changed by a second thread while the first thread is in the process of changing it, lock the object, not the dictionary.

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