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

后端 未结 5 958
时光说笑
时光说笑 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:03

    I have a feeling that you need to call GC.WaitForPendingFinalizers() as I expect that week references are updated by the finalizers thread.

    I had issues with the many years ago when writing a unit test and recall that WaitForPendingFinalizers() helped, so did making to calls to GC.Collect().

    The software never leaked in real life, but writing a unit test to prove that the object was not kept alive was a lot harder then I hoped. (We had bugs in the past with our cache that did keep it alive.)

提交回复
热议问题