-
Notifications
You must be signed in to change notification settings - Fork 8
/
Program.cs
51 lines (42 loc) · 1.25 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Runtime.CompilerServices;
namespace WeakRefs;
internal class Program
{
private static WeakCache<string, byte[]> cache = new();
private static byte[]? data = new byte[100];
private static void Main(string[] args)
{
AddData();
CheckStillAvailable();
GC.Collect();
CheckStillAvailable();
SetOnlyRootToNull();
GC.Collect();
CheckNoLongerAvailable();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void AddData()
{
cache.Add("d", data!);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CheckStillAvailable()
{
Console.WriteLine("Retrieval: " +
cache.TryGetValue("d", out byte[]? fromCache));
Console.WriteLine("Same ref? " +
object.ReferenceEquals(data, fromCache));
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void SetOnlyRootToNull()
{
data = null;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CheckNoLongerAvailable()
{
byte[]? fromCache;
Console.WriteLine("Retrieval: " + cache.TryGetValue("d", out fromCache));
Console.WriteLine("Null? " + (fromCache == null));
}
}