Garbage Collection should have removed object but WeakReference.IsAlive still returning true

后端 未结 5 956
时光说笑
时光说笑 2020-12-06 05:50

I have a test that I expected to pass but the behavior of the Garbage Collector is not as I presumed:

[Test]
public void WeakReferenceTest2()
{
    var obj =         


        
5条回答
  •  无人及你
    2020-12-06 06:20

    As far as I know, calling Collect does not guarantee that all resources are released. You are merely making a suggestion to the garbage collector.

    You could try to force it to block until all objects are released by doing this:

    GC.Collect(2, GCCollectionMode.Forced, true);
    

    I expect that this might not work absolutely 100% of the time. In general, I would avoid writing any code that depends on observing the garbage collector, it is not really designed to be used in this way.

提交回复
热议问题