Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does garbage collector clear objects subscribed to events?

If I do the following:

public class Test
{
    public static void Main()
    {
        List<Person> persons = new List<Person> { new Person() };

        persons[0].Sneezing += new EventHandler(Person_Sneezing);

        persons = null;
    }

    public static void Person_Sneezing(object sender, EventArgs e)
    {
        (sender as Person).CoverFace();
    }
}

Does the person that was in person[0] still exists in memory because it's Sneezing delegate has a reference to the Person_Sneezing method or does it get collected by the GC?

like image 454
Carlo Avatar asked May 29 '09 21:05

Carlo


People also ask

What does garbage collection clean up?

In the common language runtime (CLR), the garbage collector (GC) serves as an automatic memory manager. The garbage collector manages the allocation and release of memory for an application. For developers working with managed code, this means that you don't have to write code to perform memory management tasks.

What does garbage collection do?

Garbage collection ensures that a program does not exceed its memory quota or reach a point that it can no longer function. It also frees up developers from having to manually manage a program's memory, which, in turn, reduces the potential for memory-related bugs.

Does garbage collector clear stack memory?

Does the garbage collector sweep stack memory? No. The garbage collector does only manage heap memory. All values on the stack are expected to be needed again when the program returns to that stack frame, so they must not be collected.

Which objects are garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects.


1 Answers

This will be collected by the GC. To be kept in memory an object must be referenced directly or indirectly by ...

  1. A value on the stack
  2. A value rooted in a strong GC handle
  3. A corner case or two I'm not thinking of at the moment

This is not true for the object at persons[0]. So it will be collected.

That is of course assuming the constructor for Person() doesn't do anything funny like add itself to ThreadLocalStorage.

like image 77
JaredPar Avatar answered Oct 26 '22 23:10

JaredPar