|
1 | 1 | // Licensed to the .NET Foundation under one or more agreements.
|
2 | 2 | // The .NET Foundation licenses this file to you under the MIT license.
|
3 | 3 |
|
4 |
| -// Tests WeakReference.IsAlive : IsAlive=true if GC has not occurred on the object |
| 4 | +// Tests WeakReference.IsAlive : IsAlive=true if GC has not occurred on the object |
5 | 5 |
|
6 | 6 |
|
7 | 7 | using System;
|
|
11 | 11 |
|
12 | 12 | public class Test_IsAlive {
|
13 | 13 | public static int[] array;
|
14 |
| - |
| 14 | + public static WeakReference weak; |
| 15 | + |
15 | 16 | [MethodImplAttribute(MethodImplOptions.NoInlining)]
|
16 | 17 | public static void CreateArray() {
|
17 | 18 | array = new int[50];
|
| 19 | + // Create the weak reference inside of CreateArray to prevent a dangling 'array' reference |
| 20 | + // from surviving inside of TestEntryPoint. |
| 21 | + weak = new WeakReference(array); |
18 | 22 | }
|
19 |
| - |
| 23 | + |
20 | 24 | [MethodImplAttribute(MethodImplOptions.NoInlining)]
|
21 | 25 | public static void DestroyArray() {
|
22 | 26 | array = null;
|
23 | 27 | }
|
24 |
| - |
| 28 | + |
25 | 29 | [Fact]
|
26 | 30 | public static int TestEntryPoint() {
|
27 | 31 | CreateArray();
|
28 | 32 |
|
29 |
| - WeakReference weak = new WeakReference(array); |
30 |
| - |
31 | 33 | bool ans1 = weak.IsAlive;
|
32 | 34 | Console.WriteLine(ans1);
|
33 |
| - |
34 |
| - if(ans1==false) { // GC.Collect() has already occurred..under GCStress |
35 |
| - Console.WriteLine("Test for WeakReference.IsAlive passed!"); |
36 |
| - return 100; |
| 35 | + if (ans1 != true) |
| 36 | + { |
| 37 | + // This should be impossible; it would indicate that either the array was collected while reachable from |
| 38 | + // our static field, or that the WeakReference failed to track the array even though it's still alive. |
| 39 | + Console.WriteLine("Test for WeakReference.IsAlive failed!"); |
| 40 | + return 2; |
37 | 41 | }
|
38 | 42 |
|
39 |
| - //else, do an expicit collect. |
| 43 | + // Release our strong reference (via static field) so that the collector will no longer see array as reachable. |
40 | 44 | DestroyArray();
|
| 45 | + // Perform a blocking full collection which will hopefully collect the array. |
41 | 46 | GC.Collect();
|
42 |
| - |
| 47 | + |
43 | 48 | bool ans2 = weak.IsAlive;
|
44 | 49 | Console.WriteLine(ans2);
|
45 | 50 |
|
|
0 commit comments