GC of delegates, what am I missing? (my delegate is not collected)

后端 未结 1 819
独厮守ぢ
独厮守ぢ 2021-01-18 00:59

I have a class that holds on to a delegate, in order to lazily evaluate something later.

Once I\'ve evaluated it, by calling the delegate, I clear out the reference

1条回答
  •  孤城傲影
    2021-01-18 01:39

    The "problem" is that the compiler is noticing that it can reuse a single delegate instance forever. It doesn't capture any context, not even the implicit this reference. So this:

    void CreateTestData(out WeakReference wr, out Lazy l)
    {
        Func f = () => 10;
        ...
    }
    

    Is turned into something like:

    static Func hiddenDelegate;
    
    static int HiddenMethod()
    {
        return 10;
    }
    
    void CreateTestData(out WeakReference wr, out Lazy l)
    {
        if (hiddenDelegate == null)
        {
            hiddenDelegate = HiddenMethod;
        }
    
        Func f = hiddenDelegate;
        ...
    }
    

    Look at the code in ildasm (or Reflector with no optimization turned on) to see exactly what's going on.

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