.Net中Immutable(不可变)集合的简单介绍



一、immutable对象的优点


1、对不可靠的客户代码库来说,它使用安全,可以在未受信任的类库中安全的使用这些对象

2、线程安全的:immutable对象在多线程下安全,没有竞态条件

3、不需要支持可变性, 可以尽量节省空间和时间的开销. 所有的不可变集合实现都比可变集合更加有效的利用内存 (analysis)

4、可以被使用为一个常量,并且期望在未来也是保持不变的




二、Immutable集合包括了下面的不可变集合:


 


System.Collections.Immutable.ImmutableArray


System.Collections.Immutable.ImmutableArray<T>


System.Collections.Immutable.ImmutableDictionary


System.Collections.Immutable.ImmutableDictionary<TKey,TValue>


System.Collections.Immutable.ImmutableHashSet


System.Collections.Immutable.ImmutableHashSet<T>


System.Collections.Immutable.ImmutableList


System.Collections.Immutable.ImmutableList<T>


System.Collections.Immutable.ImmutableQueue


System.Collections.Immutable.ImmutableQueue<T>


System.Collections.Immutable.ImmutableSortedDictionary


System.Collections.Immutable.ImmutableSortedDictionary<TKey,TValue>


System.Collections.Immutable.ImmutableSortedSet


System.Collections.Immutable.ImmutableSortedSet<T>


System.Collections.Immutable.ImmutableStack


System.Collections.Immutable.ImmutableStack<T>


 


三、Immutable常见的使用场景


Immutable由于具有不可变性,具有线程安全特性,因此比较适宜于多线程场景。


 


例如,在遍历的时候,为了防止遍历期间集合被破坏,传统的做法如下


    lock (list)
    {
        foreach (var item in list)
        {
            //do something
        }
    }


如果遍历的时间较长,会长期锁定集合,导致其它的调用处饿死,并且还需要避免死锁。


使用Immutable集合线程安全,可以不用加锁直接遍历,不仅性能更加优异,代码也更加优雅,能帮助我们快速实现稳定高效的程序。


 

 

文章转载自:  .Net中Immutable(不可变)集合    http://www.studyofnet.com/news/1032.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值