SyncLock 在 .Net 中如何工作
我有一个由多个线程共享的对象列表,它有时在尝试清除
时生成IndexOutOfRangeException。在寻找解决方案时,我发现我应该在访问列表时使用 SyncLock。
但我的问题是 lockObject
在 SyncLock
块中的重要性是什么 例如,在清除 myList
时 我可以使用
Synclock myList
myList.Clear
End SyncLock
还是lockObject应该与myList不同?
编辑:
我对sysnclock的看法是“为指定为lockObject的对象获得锁定”。如果我指定要清除的列表为 lockObject,编译器不应该在清除列表之前获得对列表的独占访问权限吗?
I have a List of objects shared by multiple threads, it sometimes generate IndexOutOfRangeException when trying to Clear
. While searching for solution I found that I should use SyncLock while accessing the List.
But my question if what is the importance of lockObject
in SyncLock
block
e.g. while clearing myList
can I use
Synclock myList
myList.Clear
End SyncLock
or lockObject should be different from myList?
Edit:
What I think about sysnclock is "lock is obtained for object specified as lockObject". What if I specify list to be cleared as lockObject, shouldn't the compiler supposed to obtain the exclusive access to list before clearing it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选择是任意的 - 引用可以完全独立于您在块中访问的数据,或者您可以使用列表引用之类的东西。
就我个人而言,我喜欢仅出于锁定的目的保留一个单独的对象 - 如果它是私有只读变量,您知道类之外的代码不会锁定相同的对象监视器。当然,如果您有许多不同的代码访问相同的共享数据,您可能需要更广泛地公开锁 - 但通常最好将获取锁需要的所有操作封装在一个操作中类,然后将锁本身保持私有。
请注意,您不应该只使用锁进行清除 - 您需要在访问列表的任何地方使用它。
The choice is arbitrary - the reference can be completely independent from the data you're accessing within the block, or you can use something like a list reference.
Personally I like to keep a separate object solely for the purpose of locking - if it's a private readonly variable, you know that no code outside the class will be locking on the same monitor. Of course, if you have lots of different code accessing the same shared data, you may need to expose the lock more widely - but it's generally preferable to encapsulate all the actions which need to acquire the lock in one class, and then keep the lock itself private.
Note that you shouldn't just use the lock for clearing - you'll need to use it everywhere that you access the list.