List< T> .AddRange()线程安全吗? [英] Is the List<T>.AddRange() thread safe?

查看:96
本文介绍了List< T> .AddRange()线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在不锁定的情况下从多个线程安全地调用List.AddRange(r)吗?如果没有,我会遇到什么麻烦?

Can I, without locking, safely call List.AddRange(r) from multiple threads? If not, what sort of trouble would I run into?

推荐答案

No, its documentation does not say it is thread safe, therefore it is not.

公共静态(在Visual Basic中共享) 此类型的成员是线程安全的. 任何实例成员都不是 保证是线程安全的.

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)的作用:

As to what can go wrong, think about what AddRange(newItems) does:

  • 检查内部阵列中是否有足够的空间
  • 如果不是:
    • 分配一个新数组
    • 将当前项目复制到新数组
    • 设置一个字段以指向新数组
    • Check if there is enough space in the internal array
    • If not:
      • Allocate a new array
      • Copy the current items to the new array
      • Set a field to point at the new array

      现在想想,如果将上述内容与对AddRange()的另一个调用甚至只是对读取项目的调用混合在一起会发生什么.

      Now think what will happen if the above is mixed up with another call to AddRange() or even just a call to read an item.

      这篇关于List< T> .AddRange()线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆