Garbage collection being successful seems to depend on non-related things

假装没事ソ 提交于 2019-12-13 16:23:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!