How does the GC collect resources in a static member in .NET?

I have a code like this:

Class Program
{
    static StreamReader sr = null;
    static int var=0;
    static Program()
    {
        sr = new StreamReader("input.txt")
    }

    ~Program()
    {
        sr.Dispose();
    }

    static void main(string args[])
    {
        //do something with input here
    }
}

This may not be good practice, but I just want to use this example to ask how the deconstructor and GC work.

My question is whether the Program () program will be called indefinitely or not at all in this case. If the deconstructor is not called, then how the GC collects unmanaged resources and managed resources.

+3
source share
4 answers

He probably will not recover these resources until the AppDomain or process has been unloaded.

, . , , - Singleton. , " ", Singleton, , . WeakReference singleton.

, , , , ... , .

+1

, .

dispose , ( ..). , , GC , null, , .

, GC . , ( ), . , "" .

+1

, . , , , . , .

Btw GC . . IDiposable / .

+1

# , (). , Program , ~Program() .

When (if) it is called, it only calls the method Dispose() StreamReader; because the link to StreamReaderis still preserved after the finalizer is called, the instance will never be garbage collected before the program exits.

+1
source

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


All Articles