-
Notifications
You must be signed in to change notification settings - Fork 56
/
Program.cs
53 lines (45 loc) · 1.41 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
52
53
using System;
using System.Runtime.CompilerServices;
namespace WeakRefs
{
class Program
{
static WeakCache<string, byte[]> cache = new WeakCache<string, byte[]>();
static byte[] data = new byte[100];
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));
}
}
}