简体   繁体   中英

When is disposed an object in a functional approach?

I am puzzling with this scenario. Consider the following basic code:

class Program
{
    /// <summary>
    /// Create a function that sums up any of the ints supplied
    /// </summary>
    private static Func<IEnumerable<int>, Func<int>> Test = (coll) =>
    {
        //create the function
        Func<int> fn = () =>
        {
            return coll.Sum();
        };

        return new Func<int>(fn);
    };



    static void Main(string[] args)
    {
        //given an ints set, create a function that sums up any of them
        int[] coll = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        Func<int> fn = Test(coll);

        //same as before: different set, and another func's instance
        coll = new[] { 5, 5, 5, 5 };
        Func<int> fn2 = Test(coll);

        //dispose any pending object
        coll = null;
        GC.WaitForPendingFinalizers();

        //evaulate both the functions in a lazy fashion
        Console.WriteLine(fn());    //yields 45
        Console.WriteLine(fn2());   //yields 20

        Console.Write("Press any key...");
        Console.ReadKey();
    }

}

The purpose is absolutely useless, but I am asking myself when the two integer arrays will be disposed. The "Test" function should return another function, that is not evaluated until will be called. That is verified by using the debugger. So far, the first "coll" array should be disposed because it is replaced by the new set. However, the first function still evaluates correctly. At this point, either I must wait a longer time for the GC, or the array will be pinned somewhere...in the second hypothesis, I'd expect the arrays would never released. Where is my error? Thanks a lot in advance.

While your original reference, coll , is set to null, the functions fn & fn2 have a reference to the same int[] array.

Therefore, the array that coll references will not be garbage collected until there are no more references to it, including the arguments to fn and fn2 .

I know the parameter within Test is a copy, but it's a copy of the reference to the array object, not a copy of the array itself.

The terms I used may not be correct. But hopefully this helps explain it.

Change your GC.WaitForPendingFinalizers(); to GC.Collect(); . This Invokes the Garbage Collection to clean up the memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM