Skip to content

Commit f2dfcbe

Browse files
committed
Add ImmutableListTest
1 parent 26fed4c commit f2dfcbe

File tree

2 files changed

+66
-3
lines changed

2 files changed

+66
-3
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System.Collections.Immutable;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
namespace CollectionTest;
6+
7+
internal class ImmutableListTest
8+
{
9+
10+
#region Constants & Statics
11+
12+
public static void CopyOnWriteTest()
13+
{
14+
var array = new[] { 1, 2, 3, 4 };
15+
var immutable = array.ToImmutableList();
16+
17+
var asImmutable = ImmutableCollectionsMarshal.AsImmutableArray(array);
18+
var as2 = Unsafe.As<int[], ImmutableArray<int>>(ref array);
19+
var as3 = ImmutableArray.Create(array);
20+
21+
array[0] = 100;
22+
Console.WriteLine(immutable[0]); // 1 发生复制
23+
Console.WriteLine(asImmutable[0]); // 100
24+
Console.WriteLine(as2[0]); // 100
25+
Console.WriteLine(as3[0]); // 1 发生复制
26+
27+
Console.WriteLine();
28+
var newImmutable = asImmutable.SetItem(1, 200);
29+
Console.WriteLine(array[1]); // 2
30+
Console.WriteLine(newImmutable[1]); // 200
31+
}
32+
33+
public static void ImmutableInterlockedTest()
34+
{
35+
var list = ImmutableList<int>.Empty;
36+
37+
// 多线程安全添加
38+
ImmutableInterlocked.Update(ref list, l => l.Add(1));
39+
ImmutableInterlocked.Update(ref list, l => l.Add(2));
40+
41+
Console.WriteLine(string.Join(", ", list)); // 1, 2
42+
}
43+
44+
public static void Test()
45+
{
46+
var list = new List<int>();
47+
var readOnly = list.AsReadOnly();
48+
var immutable = list.ToImmutableList();
49+
50+
list.Add(1);
51+
Console.WriteLine(readOnly.Count); // 1
52+
Console.WriteLine(immutable.Count); // 0
53+
54+
var newList = immutable.Add(2);
55+
Console.WriteLine(immutable.Count); // 0
56+
Console.WriteLine(newList.Count); // 1
57+
}
58+
59+
#endregion
60+
61+
}

src/Tests/CollectionTest/Program.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
using BenchmarkDotNet.Running;
2-
31
namespace CollectionTest;
42

53
internal sealed class Program
@@ -17,7 +15,11 @@ private static void Main(string[] args)
1715

1816
//Console.ReadLine();
1917

20-
BenchmarkRunner.Run<FrozenCollectionBenchmark>();
18+
//BenchmarkRunner.Run<FrozenCollectionBenchmark>();
19+
20+
//ImmutableListTest.Test();
21+
//ImmutableListTest.CopyOnWriteTest();
22+
ImmutableListTest.ImmutableInterlockedTest();
2123
}
2224

2325
#endregion

0 commit comments

Comments
 (0)