When is a .net object = null for garbage collection? Does volume matter?

People,

If I set a large object in .net to zero in the middle of a long-term method (not necessarily an intensive intensive processor ... just a long-term one), this is a garbage collection game right away OR should this method complete before the object is ready to collect garbage?

+4
source share
3 answers

The method does not need to be populated, but you also do not need to set the variable to null if the GC can say that you are not going to read it again. For instance:

public void Foo()
{
    SomeObject x = new SomeObject();
    // Code which uses x

    Console.WriteLine("Eligible for collection");

    // Code which doesn't use x.
}

- , , . , - . , , GC , , GC. :

using System;

class Bomb
{
    readonly string name;

    public Bomb(string name)
    {
        this.name = name;
    }

    ~Bomb()
    {
        Console.WriteLine(name + " - going boom!");
    }    

    public override string ToString()
    {
        return name;
    }
}

class Test
{
    static void Main()
    {
        Bomb b = new Bomb("First bomb");
        Console.WriteLine("Using bomb...");
        Console.WriteLine(b);
        Console.WriteLine("Not using it any more");

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("Creating second bomb...");
        b = new Bomb("Second bomb");
        Console.WriteLine("Using second bomb...");
        Console.WriteLine(b);
        Console.WriteLine("End of main");
    }
}

:

Using bomb...
First bomb
Not using it any more
First bomb - going boom!
Creating second bomb...
Using second bomb...
Second bomb
End of main
Second bomb - going boom!

, : , " ", GC , . , :

using System;

class Bomb
{
    int x = 10;

    ~Bomb()
    {
        Console.WriteLine("Boom!");
    }

    public void GoBang()
    {
        Console.WriteLine("Start of GoBang");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("x={0}", x);
        Console.WriteLine("No more reads of x");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("Returning");
    }
}

class Test
{
    static void Main()
    {
        Bomb b = new Bomb();
        b.GoBang();
        Console.WriteLine("Still in Main");
    }
}

:

Start of GoBang
x=10
No more reads of x
Boom!
Returning
Still in Main

( - , .)

: null... . null. .

+7

. ?. , , , null.

Scope , , , . .

+7

Assuming the previously stored value no longer refers to anything, it immediately has the right to garbage collection.

+1
source

All Articles