2 using System
.Threading
;
3 using System
.Collections
.Generic
;
4 using System
.Runtime
.InteropServices
;
6 namespace WeakReferenceTest
8 public static class Cache
{
9 static GCHandle
[] table
= new GCHandle
[1024 * 1024];
11 public static T Probe
<T
>(int hc
) where T
: class
13 int index
= hc
& (table
.Length
- 1);
16 var wr
= table
[index
];
19 return wr
.Target
as T
;
23 public static T Add
<T
>(T obj
, int hc
) where T
: class
25 int index
= hc
& (table
.Length
- 1);
28 table
[index
] = GCHandle
.Alloc (obj
, GCHandleType
.Weak
);
36 public static readonly int seed
= unchecked(DateTime
.Now
.Ticks
.GetHashCode());
38 Random rand
= new Random(seed
);
46 thread
= new Thread(new ThreadStart(Work
));
54 var item
= rand
.Next ();
55 var probed
= Cache
.Probe
<object>(item
.GetHashCode());
58 Cache
.Add
<object>(item
, item
.GetHashCode());
61 if (rand
.NextDouble() <= 0.1) {
75 static class RandHelper
{
76 public static string RandString(this Random rand
, int len
)
78 char[] table
= new char[len
];
79 for (int idx
= 0; idx
< len
; idx
++) {
80 table
[idx
] = (char) ('a' + idx
);
82 return new string(table
, 0, len
);
88 public static void Main (string[] args
)
90 Console
.WriteLine("Starting cache testers");
91 Console
.WriteLine("Thread seed: " + Tester
.seed
);
92 List
<Tester
> testers
= new List
<Tester
>();
93 for (int count
= 0; count
< 10; count
++) {
94 testers
.Add(new Tester());
97 foreach (var tester
in testers
) {
101 for (int i
= 0; i
< 4; ++i
)
103 Thread
.Sleep(TimeSpan
.FromSeconds(1));
106 foreach (var tester
in testers
)