strange WeakReference behavior on Mono

前端 未结 2 1716
猫巷女王i
猫巷女王i 2021-01-07 23:38

Testing code that uses WeakReference failed for me using Mono 2.11.3 (SGen) as well as the stable 2.10.8 version. In a simple code like this

object obj = new         


        
相关标签:
2条回答
  • 2021-01-08 00:13

    It is not a bug, but an implementation detail where the Mono GC behaves differently from the MS GC. In this case, since you created the object obj in the same stack frame, it happens to be kept alive by the conservative stack scanning code. In real code (as opposed to trivial test cases like this) this is not a problem. If for your particular case it is, I suggest allocating the object and its WeakReference in a separate method:

    static WeakReference Alloc ()
    {
        return new WeakReference (new object ());
    }
    
    0 讨论(0)
  • 2021-01-08 00:16
    [MethodImpl((MethodImplOptions.NoInlining)]
    static WeakReference Alloc ()
    {
        return new WeakReference (new object ());
    }
    

    Must ensure Alloc() method not be inline when compile

    0 讨论(0)
提交回复
热议问题