我可以在不锁定的情况下从多个线程安全地调用 List.AddRange(r) 吗?如果不是,我会遇到什么样的麻烦?
最佳答案
否,its documentation没有说它是线程安全的,因此它不是。
Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
至于哪里会出错,想想 AddRange(newItems) 做了什么:
- 检查内部数组是否有足够的空间
- 如果不是:
- 分配一个新数组
- 将当前项复制到新数组
- 设置一个字段指向新数组
- 将newItems复制到内部数组中正确的local
- 更新“计数”字段(这用于控制插入下一项的位置)
现在想一想,如果将上述内容与对 AddRange() 的另一个调用或什至只是对读取项目的调用混合在一起,会发生什么情况。
关于c# - List<T>.AddRange() 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4043662/