勇哥注:
不可变对象集合类由于其特性,天生就是线程安全的,多线程同时读写都没得问题。
它一共有下面这些:
ImmutableArray<T>
ImmutableStack<T>
ImmutableQueue<T>
ImmutableList<T>
ImmutableHashSet<T>
ImmutableSortedSet<T>
ImmutableDictionary<K, V>
ImmutableSortedDictionary<K, V>
但是这种集合在频繁修改的时候开销就比较大。
下面勇哥写一个示例程序:

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        ImmutableList<int> list1= ImmutableList.Create<int>();
     
        public Form1()
        {
            InitializeComponent();
           
        }
        private void button1_Click(object sender, EventArgs e)
        {
            
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Random ran = new Random();
                    var list2 = list1.ToBuilder();
                    list2.Add(ran.Next(0,1000));
                    list1 = list2.ToImmutable();
                   
                    Thread.Sleep(1300);
                    
                }
            });
          
            
        }
        private void button2_Click(object sender, EventArgs e)
        {
         
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Random ran = new Random();
                    var list2 = list1.ToBuilder();
                    list2.Add(ran.Next(0,1000));
                    list1 = list2.ToImmutable();
                    Thread.Sleep(1800);
                }
            });
        }
        private void button3_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Start();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            var sb1 = new StringBuilder();
            for(int i=0;i<list1.Count;i++)
            {
                sb1.Append(list1[i] + ",");
            }
            RtbMsg.Text = sb1.ToString();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            list1=list1.RemoveAt(0);
        }
    }
}另一有篇介绍不可变对象集合见下面文章:
另外,此集合不是.net Framework自带的,你得去Nuget去下载,下载关键字如下:

---------------------
作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!


少有人走的路


















