问题
I'm trying to consistently force objects to be garbage collected, for purposes of writing unit-tests related to weak references.
However, GC.Collect()
, which I expect to force garbage collection, does not seem to behave consistently.
Consider the following example code.
static void Main (string [] args)
{
var obj = new object ();
var wRef = new WeakReference (obj);
obj = null;
GC.Collect ();
Console.WriteLine (wRef.IsAlive); // Prints false.
Console.ReadKey ();
}
In the code above the object seems to be collected, while in the code below this is not the case, although the code is virtually the same.
static void Main (string [] args)
{
var obj = new object ();
var wRef = new WeakReference (obj);
obj = null;
GC.Collect ();
bool alive = wRef.IsAlive ? true : false;
Console.WriteLine (alive); // Prints true
Console.ReadKey ();
}
Can someone explain this behavioral difference, and show how we can reliably have objects getting reclaimed in order to do some testing with weak references?
Update
When running the second snippet in release mode without a debugger attached (i.e. outside Visual Studio) it prints False.
来源:https://stackoverflow.com/questions/34399139/garbage-collection-being-successful-seems-to-depend-on-non-related-things