当前位置:网站首页>Garbage collection of C closure

Garbage collection of C closure

2022-06-25 00:23:00 Moyiii

Today, when analyzing the problems of project memory release and garbage collection , Noticed a problem , If a variable is referenced by a closure , Will not be recycled ( This is nonsense in theory ), That's it , This problem becomes very difficult to check . It means , Some buttons are bound to events with closures , This part of memory is hard to recycle . Here's an example :

public class B
{
    public int Name;
}

class TestClass
{
    private Action action;
    private static WeakReference<B> weak;
    
    public void GenerateClosure()
    {
        B b = new B();
        weak = new WeakReference<B>(b);
        action = () =>
        {
            Console.WriteLine(b.Name);
        };
    }

    public void ReleaseClosure()
    {
        action = null;
    }

    public void OverWatchGC()
    {
        if (weak.TryGetTarget(out B b))
        {
            Console.WriteLine("B Not recycled ");
        }
        else
        {
            Console.WriteLine("B It's recycled ");
        }
    }
}


class Program
{
    public static void Main(string[] args)
    {
        TestClass c = new TestClass();
        c.GenerateClosure();
        GC.Collect();
        c.OverWatchGC();
        c.ReleaseClosure();
        GC.Collect();
        c.OverWatchGC();
    }
}

give the result as follows :

B Not recycled
B It's recycled
 

If the function where the closure is located is a static function , Recycling will be more troublesome , I'm testing , Even if you put action Set as null, Garbage collection has not been successful B References to .

So be careful, be careful, be careful , Sometimes a dot accumulates , It is a very difficult problem to check

原网站

版权声明
本文为[Moyiii]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206241943591138.html