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

后端 未结 1 818
独厮守ぢ
独厮守ぢ 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<int> l)
    {
        Func<int> f = () => 10;
        ...
    }
    

    Is turned into something like:

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

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

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