AssertGC .NET version: tesing module memory leaks

I am trying to write unit test using .NET 4 to ensure that an object can be collected from garbage after running some code. In Java, I would use assertGC to provide weak link collection. How can I write this type of test for .NET?

I tried to save the object WeakReferenceand call GC.Collect(), but, as expected, sometimes my object is collected, and sometimes not. Note that this is for unit test, not production code. I would not want GC.Collect () in my real code base.

I use C #, but the same answer will be useful for VB.NET as well.

+3
source share
2 answers

This seems to be impossible at the moment with .NET 4. Although you can find out if an object cannot be garbage collected (for example, have a link to it), there is no way to deterministically know if an object can be garbage collected.

Using a WeakReference or finalizer (and calling GC.Collect ()) can collect the object, but if it is not in generation 0, it is likely that it will not.

Literature:

0
source

Try the following:

5 , ... , -?

using System;

internal class Program
{
    private static void Main(string[] args)
    {
        int cnt = 0;
        while (true)
        {
            ++cnt;
            bool gced = false;
            Action handler = () => gced = true;
            new Foo(handler);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Console.Out.WriteLine("{0} : {1}", cnt, gced);
            if (!gced)
            {
                throw new Exception("WTF?");
            }
        }
    }
}
class Foo
{
    private readonly Action _onFinalized;

    public Foo(Action finalized)
    {
        _onFinalized = finalized;
    }

    ~Foo()
    {
        if (_onFinalized != null) _onFinalized();
    }
}
+1

Source: https://habr.com/ru/post/1759495/


All Articles