Testing/Verifying a WeakReference

前端 未结 3 1943
逝去的感伤
逝去的感伤 2021-02-12 22:29

I\'d like to verify that code setting up a WeakReference does not accidentally hold a strong reference to the referenced object. (Here\'s an example of how it is easy to acciden

3条回答
  •  执笔经年
    2021-02-12 22:59

    I did this just yesterday. Here's what I had to add to ensure the collection happened prior to your last assert:

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.WaitForFullGCComplete();
            GC.Collect();
    

    If after this .IsAlive is still true, it's likely there is still a strong reference somewhere.

    Incidentally - Be sure to NOT check .IsAlive when you access your WeakReference target. To avoid a race condition between you checking .IsAlive and .Target, do this:

    var r = weakRef.Target AS Something;
    if (r != null)
    {
        ... do your thing
    }
    

提交回复
热议问题