c# - Does the garbage collector know to dispose variables located in a lambda-captured scope? - Stack Overflow

admin2025-04-21  2

In this C# example, will the garbage collector dispose of hugeString after TestClass is instantiated?

Furthermore, would uncommenting the line hugeString = null help garbage collection at all?

public sealed class TestClass
{
    public TestClass()
    {
        var hugeString = new string('0', 100000000);
        var length = hugeString.Length;
        GetLength = () => length;
        // hugeString = null; // do I need to do this?
    }
    public readonly Func<int> GetLength;
}
转载请注明原文地址:http://anycun.com/QandA/1745227229a90480.html