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

来源:互联网 发布:长春办公软件培训班 编辑:程序博客网 时间:2024/06/05 15:51


一、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 itemin list)
        {
            //do something
        }
    }


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


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


 

 

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


0 0
原创粉丝点击