简体   繁体   中英

2 weak references to the same object show different info

I have a program in which I allocated an int array and want to check whether it will be garbage collected after I call GC.Collect() . In this program I allocate an int array array1 and keep a WeakReference to it in order to check whether it's garbage-collected later. I have a method called procedure that allocates a new, local array in it ( array2 ) and assigns array2 to an input temp array passed by reference. This method also assigns weak references ref1 and ref2 to hold info about an input temp array and array2 . When I call this method, I pass array1 to it, so array1 becomes equal to array2 . Once I exit the method, I call GC.Collect() to force garbage collection. Debugger tells ref1 and ref2 still have IsAlive property equal to true . ref3 , which is instantiated in the main function and references array1 , tells that IsAlive property is false after garbage collection, so array1 has already been garbage-collected.

Shouldn't ref1 , which references array1 , have IsAlive property equal to false , just as ref3 (which also references array1 ) does?

static WeakReference ref1;
static WeakReference ref2;
static WeakReference ref3;

const int max_size = 10;
public static void procedure(ref int []temp)
{
    int[] array2 = new int[max_size];

    temp = array2;

    for (int i = 0; i < max_size; i++)
        array2[i] = i * 2;

    ref1 = new WeakReference(temp);
    ref2 = new WeakReference(array2);
}

static void Main(string[] args)
{
    int []array1 = new int[max_size];

    ref3 = new WeakReference(array1);

    procedure(ref array1);
    //array1 = null;
    GC.Collect();
}

I think you've gotten confused between your variables and the values they point to. At the point you call GC.Collect() , array1 , ref1 , ref2 are all pointing to the array created in procedure() ( array1 being the only strong reference alive).

Trace through your code manually keeping track of each value (the array created in procedure(), the array created in Main()), and which variable points to which at every point.

You'll see that at the point where you create the two WeakReferences in procedure(), temp and array2 point to the same value (the array created in the same method). The WeakReference created in Main() will be the only thing left pointing to the array created in Main(), since the array1 variable will be changed to point to the other array by procedure() due to the ref .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM